Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 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 Reply

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...