Question

$products = Product::with(
    array(
        'productDescriptions' => function($query) {
             $query->lang(App::getLocale());
         },
        'productImages' => function($query) {
             $query->imageType('thumbnail');    
        }))
    ->paginate($items_per_page);

Hi, is there an easy way to eager load relationships but only if they exists? More specifically I would like to get only these products, if their productDescriptions are not empty. In SQL I would simply do a inner join, but how to do it an easy way in Eloquent? I could foreach over all returned products and check if $product->productDescription->count() > 0 but maybe there is simpler way to achieve that.

Was it helpful?

Solution

There are 2 methods for this: has and whereHas:

$products = Product::with(   // this part will load the relation
  array(
    'productDescriptions' => function($query) {
         $query->lang(App::getLocale());
     },
    'productImages' => function($query) {
         $query->imageType('thumbnail');    
    }))
  ->has('productDescriptions') // this will make sure only Products having related descriptions will be fetched
  ->paginate($items_per_page);

OTHER TIPS

You can do Eager Load Constraints as seen in the docs.

So you would need to do something LIKE this (not tested - but you get the idea):

$products = Product::with(
    array(
        'productDescriptions' => function($query) {
             $query->where('productDescription', '!=', '')->lang(App::getLocale());
         },
        'productImages' => function($query) {
             $query->imageType('thumbnail');    
        }))
    ->paginate($items_per_page);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top