skip to Main Content

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:

  1. Only select certain fields from the cooking_methods model
  2. 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


  1. Maybe you can try something like this. Not tested. But Hopefully, this will work.

    $site->sales()->with([
        'recipes' => function ($query) {
            $query->with([
                'cooking_methods' => function ($query) {
                    $query->with(['ingredient.suppliers'])
                        ->select(['ingredient_id', 'field_1', 'field_2']); // ingredient_id for relation
                }
            ]);
        }
    ]);
    
    Login or Signup to reply.
  2. Here’s an example of how you can order chained with() statements in Laravel Eloquent:

    $users = User::with('posts', 'comments')
                 ->with('profile')
                 ->get();
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search