我有这样的查询:
$users = User::with("purchases")->has("purchases",">",10)->orderBy("id","desc")->get();
我想通过购买计数来订购结果。例如,最高买家应该在顶部,反之亦然。有没有办法做到这一点?
答案 0 :(得分:1)
查看this,您可以尝试:
$users = User::with("purchases")
->has("purchases",">",10)
->orderBy("id","desc")
->get()
->sortBy(function($user){
return $user->purchases->count();
});
不能在sql中对它进行排序,但应该完成这项工作。
答案 1 :(得分:1)
如果您想让数据库(而不是PHP)对结果进行排序,则必须使用连接。像这样:
$users = User::with('purchases')
->selectRaw('users.*, count(purchases.user_id) as aggregate')
->leftJoin('purchases', 'purchases.user_id', '=', 'users.id')
->groupBy('purchases.user_id')
->having('aggregate', '>', 10)
->orderBy('aggregate', 'desc')
->get();
它看起来有点乱,因此您可以提取到查询范围并执行以下操作:
$users = User::with('purchases')->orderByHas('purchases', '>', 10, 'DESC')->get();
并将其添加到您的基本模型(或仅用户模型):
public function scopeOrderByHas($query, $relation, $operator = '>=', $count = 1, $dir = 'DESC') {
$table = $this->getTable();
$relation = $this->$relation();
$relatedTable = $relation->getRelated()->getTable();
$primaryKey = $this->primaryKey;
$foreignKey = $relation->getForeignKey();
return $query->selectRaw("{$table}.*, count({$foreignKey}) as aggregate")
->leftJoin($relatedTable, $foreignKey, '=', "{$table}.{$primaryKey}")
->groupBy($foreignKey)
->having('aggregate', $operator, $count)
->orderBy('aggregate', $dir);
}