Reputation: 24069
I query a relationship:
return User::with(array('product' => function($q){
$q->where('published', 1);
}))->get();
If a product is not published, the relationship is null.
If the product is not published, I also want to not return the user.
For example, the query should get all users who have a published product. If the user does not have a published product, do not return them.
Is this possible? Or will I just have to do some checking on the view and not output the user if product is null?
Upvotes: 0
Views: 42
Reputation: 9868
So if I understand you correctly you want to return only users that have a product that is published?
If so you're looking for the whereHas()
function, this allows you to return results of the parent model based on parameters of the relation.
return User::whereHas('product', function($query)
{
$query->where('published', true);
})->get();
Upvotes: 1