Home > Back-end >  Query More than one relationship from a model with() in Laravel
Query More than one relationship from a model with() in Laravel

Time:03-25

I need help to query a model base on its relationship:

I have a model called StoreStock, this model is related to a Product model, which has two model relationships, MasterList and Price.

I want to get all storeStock with two Product relationships.

I know i can do something like

StoreStock::all()->with('product.price')
->get()

With this, i can only pick either price or masterlist

CodePudding user response:

Pass array of relationship to with method

 StoreStock::with(['product.price','product.masterlist']) ->get() 

CodePudding user response:

A little bit explanation here, many of the Laravel methods which support string, also support arrays. You can hover over the specific method and get the intellisense. In your case, it can be written like:

StoreStock::with(['product.price','product.masterlist'])->get()

If you want to run a specific action over any specific relation, you can also write it like this:

StoreStock::with(['product.price' => function(Builder $query) {
      // your action required with the query
},'product.masterlist']) ->get()

Hope someone finds this helpful

  • Related