Skip to content
Advertisement

How to make multi table eloquent query in laravel 8?

I have two models named as ‘Products’ and ‘Product_options’ each product has many options.

I want to select those products that have at least one option where available is true.

I’ve come this far,

class Product extends Model
{
    use HasFactory;
    
    public function options()
    {
        return $this->hasMany(Product_options::class, 'product_id', 'id');
    }
}
$products = Product::whereDoesntHave('options', function ($query) {
                $query->where('available','not', ' 1');
                })
           ->has('options', '>',  0)
           ->get();

dd($products);

but if one products has one or more options where avaible is true and one or more options when it is false it doesnt selects the products.

p.s. Sorry for my english.

Advertisement

Answer

You should be able to use whereHas. It defaults to >= 1 for the count:

Product::whereHas('options', fn ($q) => $q->where('available', true))
    ->get();

Should read as, get all products that have any options where ‘available’ is ‘true’.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement