Laravel 5 asks for multiple limitation on active boot

My controller has the following code:

//Example Data; $date = Carbon::now(); $order = 'name'; // it can be by name, id or created_at; // Approach i try for getting data of user with eager loaded products //1st approach $user = User::with([ 'products' => function ($query) use ($date, $order) { $query->where('created_at', $date)->orderBy($order, 'desc'); }, ])->get(); //2nd approach $user = User::with([ 'products' => function ($query) use ($date, $order) { $query->where('created_at', $date); $query->orderBy($order, 'desc'); }, ])->get(); 

In both approaches, only the 1st request condition is read.

I want to make a suggestion of 1 where() and 1 orderBy to filter in the loaded data.

Is there something I missed? Can I put it right?

+5
source share
4 answers

I solve the problem by adding a closure to the where() condition.

 $user = User::with([ 'products' => function ($query) use ($date, $order) { $query->where(function ($q) use ($date, $order) { $q->where('created_at', $date); //This can accept more where() condition })->orderBy($order,'DESC'); }])->get(); 
+1
source

Try using the nested download. Sort of:

 $user = User::with([ 'products' => function ($query) use ($date) { $query->where('created_at', $date); },'products.order' =>function ($query) use ($order) { $query->orderBy($order, 'desc'); } ])->get(); 
+4
source

The fact is that your orderBy is created in the "subquery". When laravel does a join (this is what it takes to load), order_by will not be relevant to you.

I think a useful solution would be to use the orderby clause outside the query, using the alias provided by laravel.

$user = User::with([ 'products' => function ($query) use ($date, $order) { $query->where('created_at', $date)->orderBy($order, 'desc'); }, ])->orderBy("$laravel_join_generated_alias.$order", 'desc')->get(); where $laravel_join_generated_alias you can use debugbar to check how this line will work.

+2
source

As your description, both approaches should work well.

Are there any areas in which ->orderBy() used ->orderBy() in the User model, so orderBy() confused with closing.

dd($query->toSql()) with closure may be useful for you.

+2
source

Source: https://habr.com/ru/post/1260491/


All Articles