【问题标题】:Order by on relationship field按关系字段排序
【发布时间】:2019-11-13 17:28:39
【问题描述】:

我怎样才能根据某事物的关系对结果集进行排序?

我正在尝试获得与此等效的 Eloquent:

SELECT * FROM users INNER JOIN roles ON users.role_id = roles.id ORDER BY roles.label DESC
Here is what I am trying (based on the documentation):

$order = 'desc';
$users = User::with(['role' => function ($q) use ($order) {
            $q->orderBy('label', $order);
        }])->paginate(10);

但它没有正确订购它们。我做错了什么?

编辑:不确定显示模型关系是否相关,但这里是:

 public function role()
    {
        return $this->belongsTo(Role::class);
    }

【问题讨论】:

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

你应该用 join 来做

User::with('role')->join('role', 'role.id', '=', 'users.id')->orderBy('role.label', $order)->paginate(10);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-03
    • 2019-04-12
    • 2021-02-07
    • 2020-01-12
    • 2021-08-28
    • 2017-11-17
    • 1970-01-01
    • 2018-06-27
    相关资源
    最近更新 更多