Search code examples
laraveleager-loading

Can eager loading be used in a model? Laravel


For example a home page controller:

public function index(){
    $proditem = Category::with('products')->get();
    return view('index', compact('proditem'));
  }

Through the Category model, I retrieve the data from the Product model using an eloquent relationship. Products have a lot of pictures, but for the card, I display the first one using the following link inside the Product model:

  public function cardImage()
  {
      return $this->hasOne(ProductImage::class)->where('position', 1);
  }

And now I don't know how to use eager loading here. After all, if I use it for Category, it will give an error, because there is no such relationship in Category, but in Product.

Also, the Laravel N + 1 Query Detector package suggests using eager loading, but I can't figure out where to write it.

enter image description here


Solution

  • you can use nested eager loading:

    $proditem = Category::with('products.cardImage')->get();