Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel query join with only latest record

Tags:

php

laravel

I'm using Laravel 5.3 and trying to return a heist with it's product and only the latest order and with the latest price history. Both joins don't return anything but if I remove the $q->latest()->first(); and replace it with a simple orderBy() I get all results. My query is:

$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();
like image 625
Jongo Avatar asked Oct 30 '22 16:10

Jongo


1 Answers

As discussed in the comments, I believe the simplest way of doing 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 :)

like image 94
prateekkathal Avatar answered Nov 09 '22 14:11

prateekkathal