Laravel 复杂范围查询关系(复习)
Laravel complex scope querying relation (for review)
我写了这个,我只是想知道这是否是最好的方法。
订单有很多交易……交易属于订单。我正在查询 ID 大于发送到履行的最后一个 ID 的订单。那我只想要已批准付款状态或离线付款类型的订单。
此代码有效,只是想知道它是否是执行此操作的最佳方法:
/**
* Get all orders pending fulfilment
*
* @param $query
* @param $last_fulfiled
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeToFulfil($query, $last_fulfiled)
{
return $query->where('id', '>', $last_fulfiled)
->where(function($query) {
$query->whereHas('transactions', function ($query) {
$query->where('status', '>=', 5);
})->orWhere('payment_method', '=', 2);
});
}
编辑:
这是 SQL 语法:
select * from `orders` where `orders`.`deleted_at` is null and `id` > ? and ((select count(*) from `transactions` where `transactions`.`order_id` = `orders`.`id` and `status` >= ?) >= 1 or `payment_method` = ?)
谢谢!
这绝对是构建此查询的正确 Laravel 方法。这几乎总是会生成一个相当不错的优化查询,通常是一个 LEFT JOIN 或一个子查询或两者的组合。
如果您想查看结果查询的最佳程度,请将 ->toSql()
添加到该查询语句的末尾,并在此处添加 post 原始查询语法。
我写了这个,我只是想知道这是否是最好的方法。 订单有很多交易……交易属于订单。我正在查询 ID 大于发送到履行的最后一个 ID 的订单。那我只想要已批准付款状态或离线付款类型的订单。
此代码有效,只是想知道它是否是执行此操作的最佳方法:
/**
* Get all orders pending fulfilment
*
* @param $query
* @param $last_fulfiled
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeToFulfil($query, $last_fulfiled)
{
return $query->where('id', '>', $last_fulfiled)
->where(function($query) {
$query->whereHas('transactions', function ($query) {
$query->where('status', '>=', 5);
})->orWhere('payment_method', '=', 2);
});
}
编辑:
这是 SQL 语法:
select * from `orders` where `orders`.`deleted_at` is null and `id` > ? and ((select count(*) from `transactions` where `transactions`.`order_id` = `orders`.`id` and `status` >= ?) >= 1 or `payment_method` = ?)
谢谢!
这绝对是构建此查询的正确 Laravel 方法。这几乎总是会生成一个相当不错的优化查询,通常是一个 LEFT JOIN 或一个子查询或两者的组合。
如果您想查看结果查询的最佳程度,请将 ->toSql()
添加到该查询语句的末尾,并在此处添加 post 原始查询语法。