Chingy's avatar
Level 6

Eager load based on the basic query's model column value

Greetings everyone! Thanks in advance for anyone that will take a look.

I have this model Product which in its index I am eager loading its image-attachments. These products also can belong to a folder. In an attempt to reduce the data load, when a product is in a folder, there is no need to eager load its image attachments. My goal is to keep the whole conditional eager loading of the images in the mySQL level and not lazy load it after I get the results. I guess it's a DB::raw that I can't figure it out

So this is the query, as simple as it can get

Product::query()
  ->select(['id', 'folder_id', 'can_be_sold', 'is_active', 'position', 'title'])
// My thoughts were something like this,
	->when(DB::raw('products.folder_id IS NULL'), function ($query) {
       $query->with('productAttachments');
   })						

But it eager loads all products ,even though they are all with their folder_ids filled

Thanks again for your replies!

0 likes
4 replies
jlrdw's avatar

I am not understanding:

when a product is in a folder, there is no need to eager load its image attachments.

I think you need a WHERE and a NOT NULL usage.

1 like
Tray2's avatar

I take it there is more than one image per product?

Can different products have the same image?

However a products table, and a product_images table should be enough, no need for complex code.

If there is no image, then you can just use a generic image for the product.

1 like
Chingy's avatar
Level 6

@tray2 , @jlrdw , thanks for your responses. You are correct, i should use the whereNotNull. Works for this case.

But my question was more of the kind to ask how would you write this as in DB::raw.

In order to alter the above case. Lets say the product has 2+ images. 1 is main, 1 is external. Rest can be whatever. Products can have both main and external type of images. Let's assume that the types of products are main and external as well.

How could I eager load (without splitting it into two separate queries) for each product the image that corresponds to the type of the product?

// I want to know how can I access and write with raw the following
Products::query()
	->with(['images' => fn ($q) => $q->where('type', '=', 'products.type')])

Thanks in advance

Please or to participate in this conversation.