Laravel 查询格式 - 加入最新行
Laravel query format - Join To the Latest row
我有两个 table 例如用户和订单。
我必须在 users.id = orders.user_id
上通过订单加入用户 - 这很好。
用户 table 在订单 table.
中具有一对多关系
我也有一些条件,比如orders.pay_type = 'xyz'
, 'orders.date = yesterday'
, 'user.status = active'
..etc.
我的问题是我需要将我的用户 table 加入最新的订单行 table 对应 user_id。
或者需要获取该用户订单 table 详细信息的最新详细信息以及用户 table 数据。
我已经试过了
->orderBy('orders.date')
->groupBy('orders.user_id')
->get();
但是o/p没有结果。
您可以在用户模型中使用以下关系
public function latest_order(){
return $this->hasOne('Order')->orderBy('orders.date', 'desc')->limit(1);
}
更新
由于您无法更改模型,您可以使用以下代码为每个用户获取最新的订单。
$user = User::first(); //get first User
$user->orders()->latest('date')->first();
If you don't want to change anything in model you can go with this method as well, which is simple query builder method.
DB::table('orders')->leftJoin('users', 'orders.user_id', 'users.id')
->groupBy('orders.user_id')
->orderBy('orders.date', 'DESC')
->get();
假设,您可能在 User.php 模型中有 "orders" 函数
您也可以使用以下方法。 (类似于已经给出的答案,但针对的是一组用户而不是一个用户。)
$users = User::all();
foreach ($users as $user) {
$latest_order = $user->orders()->where('pay_type', 'xyz')->orderBy('date', 'DESC')->first(); // Option 1
$latest_order = $user->orders()->where('pay_type', 'xyz')->latest('date')->first(); // Option 2
}
$data= users::leftJoin('orders', function($join) {
$join->on('orders.user_id', '=', 'users.id')
->on('orders.id', '=', DB::raw("(SELECT max(id) from orders WHERE orders.user_id = users.id)"));
})
->select(*)
这解决了我的问题。
我有两个 table 例如用户和订单。
我必须在 users.id = orders.user_id
上通过订单加入用户 - 这很好。
用户 table 在订单 table.
我也有一些条件,比如orders.pay_type = 'xyz'
, 'orders.date = yesterday'
, 'user.status = active'
..etc.
我的问题是我需要将我的用户 table 加入最新的订单行 table 对应 user_id。 或者需要获取该用户订单 table 详细信息的最新详细信息以及用户 table 数据。
我已经试过了
->orderBy('orders.date')
->groupBy('orders.user_id')
->get();
但是o/p没有结果。
您可以在用户模型中使用以下关系
public function latest_order(){
return $this->hasOne('Order')->orderBy('orders.date', 'desc')->limit(1);
}
更新
由于您无法更改模型,您可以使用以下代码为每个用户获取最新的订单。
$user = User::first(); //get first User
$user->orders()->latest('date')->first();
If you don't want to change anything in model you can go with this method as well, which is simple query builder method.
DB::table('orders')->leftJoin('users', 'orders.user_id', 'users.id')
->groupBy('orders.user_id')
->orderBy('orders.date', 'DESC')
->get();
假设,您可能在 User.php 模型中有 "orders" 函数
您也可以使用以下方法。 (类似于已经给出的答案,但针对的是一组用户而不是一个用户。)
$users = User::all();
foreach ($users as $user) {
$latest_order = $user->orders()->where('pay_type', 'xyz')->orderBy('date', 'DESC')->first(); // Option 1
$latest_order = $user->orders()->where('pay_type', 'xyz')->latest('date')->first(); // Option 2
}
$data= users::leftJoin('orders', function($join) { $join->on('orders.user_id', '=', 'users.id') ->on('orders.id', '=', DB::raw("(SELECT max(id) from orders WHERE orders.user_id = users.id)")); }) ->select(*)
这解决了我的问题。