laravel查询只与最新记录联接

Jon*_*ngo 5 php laravel

我正在使用Laravel 5.3并尝试使用它的产品返回抢劫,只有最新的订单最新的价格历史.两个连接都没有返回任何东西,但是如果我删除$q->latest()->first();它并用一个简单的替换它orderBy()我得到所有结果.我的查询是:

$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();
Run Code Online (Sandbox Code Playgroud)

Cha*_*her 1

调用first()与调用take(1)->get()[0]相同;意思是限制返回的数量为1并返回。你想要的只是极限部分。因此,如果将first()更改为take(1)。

更新

$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();
Run Code Online (Sandbox Code Playgroud)