I’m working with Laravel 8…
So I have the following eloquent query, I’ve eager loaded a bunch of models but I want to do 2 things to the way the models are loaded:
- Only select certain fields from the cooking_methods model
- Order the suppliers by a priority column, and take only the first one
$sales = $site->sales() ->with('recipes.cooking_methods.ingredient.suppliers')->whereBetween('deliver_by',[$end,$start])->where('status','pending')->get();
I’ve seen that you can attach a function to individual models but is there a way to attach them inline? Can’t see it in the docs.
Any wizards on here that can help with that?
I’ve seen that you can attach a function to individual models but is there a way to attach them inline? Can’t see it in the docs.
Any wizards on here that can help with that?
3
Answers
Maybe you can try something like this. Not tested. But Hopefully, this will work.
Here’s an example of how you can order chained with() statements in Laravel Eloquent:
You can try use Nested Eager Loading you can use an array in
->with
method, but you need write relationship in Sale Model, change$site
for Sale Model with where clause.The second point check ordering
->orderBy('field','asc')
functions and use->first()
method to get it. The Query builder methods works in ORM Models.