Reputation: 2243
Tables
VENDOR
id name approved
PRODUCT
id name price instock fky_prod_vendor_id
Relationship
VENDOR(hasMany products()) <- (one-to-many) -> (hasOne vendor())PRODUCT
Query
How can I get all the products in-stock of a approved vendor using Eloquent given that the relationships are defined in Model?
My SQL is as following, but I need to use Eloquent relationship to achive the following.
select product.id
from product, vendor
where product.fky_prod_vendor_id = vendor.id
and vendor.approved = 'y'
and product.instock > 0
Thanks
K
Upvotes: 1
Views: 1692
Reputation: 2243
As relationships are present, we can achieve this using Querying Relationship Existence method whereHas as rightly pointed out by @svrnm
PRODUCT::where('instock','>',0)
->whereHas('vendor', function ($query) { // Using Eloquent Query Existence, first parameter is name of relationship method, inside function is where clause on related model
$query->where('approved','y');
})->get();
That's magic of Laravel
Thanks
K
Upvotes: 1