Laravel request only connects to last record

I use Laravel 5.3 and try to return a cheb with this product and only the last order and with the latest price history , Both connections return nothing, but if I delete $q->latest()->first(); and replace it with simple orderBy() , I will get all the results. My request:

 $data = $heist->with(['product'=> function($query) { $query->with(['orders' => function($q) { return $q->latest()->first(); }]); $query->with(['price_history' => function($q) { return $q->latest()->first(); }]); }])->orderBy('completed_at', 'DESC')->orderBy('active', 'DESC')->get(); 
+5
source share
2 answers

The call to first () is the same as the call to take (1) โ†’ get () [0]; This means that the amount returns to 1 and returns it. What you want is just the limit. Therefore, if you change first () to accept (1).

Update

 $data = $heist->with([ 'product'=> function($query) { $query->with( [ 'orders' => function($q) { $q->latest()->take(1); }, 'price_history' => function($q) { $q->latest()->take(1); } ] ); } ])->orderBy('completed_at', 'DESC')->orderBy('active', 'DESC')->get(); 
+1
source

As discussed in the comments, I believe the easiest way to do this is:

 $heists = $heist->with(['product'=> function($query) { $query->with([ 'orders' => function($q) { return $q->orderBy('created_at', 'desc')->take(1)->get(); }, 'price_history' => function($q) { return $q->orderBy('created_at', 'desc')->take(1)->get(); } ]); }])->orderBy('completed_at', 'desc')->orderBy('active', 'desc')->get(); 

Hope this helps :)

+1
source

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


All Articles