Search code examples
laravelmany-to-manylaravel-8

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?


Solution

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