Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

many to many - Laravel check hasMany of hasMany relationship if has IDs?

Hello I have the following relationship setup:

Product class:

public function attributes()
    {
        return $this->hasMany(ProductAttribute::class);
    }

ProductAttribute class:

public function attribute()
    {
        return $this->belongsTo(Attribute::class);
    }

    public function values()
    {
        return $this->hasMany(ProductAttributeValue::class, 'product_attribute_id');
    }

ProductAttributeValue class:

public function attributeValue()
    {
        return $this->belongsTo(AttributeValue::class, 'attribute_value_id');
    }

How to check if Product has values with ids 5 and 15?

I am trying to make a query like this:

Product::whereHas('values', function($q) use ($product_values_ids) {
                    $q->whereIn('attribute_value_id', $product_values_ids);
                })->get();

however it is not working. I cannot access directly $product->values.

Any suggestions on how to access directly the values of attributes from the Product?

Update:

I have just managed to make it work with a many to many trough relationship:

Product class:

public function values()
    {
        return $this->hasManyThrough(ProductAttributeValue::class, ProductAttribute::class);
    }

is there a way to get only the results that have all the ids listed in the $product_values_ids array?

question from:https://stackoverflow.com/questions/65919270/laravel-check-hasmany-of-hasmany-relationship-if-has-ids

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to add new relation to Product model:

public function values(): HasManyThrough
{
    return $this->hasManyThrough(ProductAttributeValue::class, ProductAttribute::class);
}

and then:

$builder = Product::query();
foreach($product_values_ids as $id) {
    $builder->whereHas('values', function($q) use ($id) {
        $q->where('id', $id);
    });
}

$product = $builder->get();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...