【问题标题】:In Laravel 7 How to orderBy Roles->name?在 Laravel 7 中如何按角色排序-> 名称?
【发布时间】:2020-06-02 12:28:59
【问题描述】:

我有UserRoles relationships 的模型,就像这样:

public function users(){

        return $this->belongsToMany(User::class)->withTimestamps();

    }

和角色模型与用户关系:

public function roles(){

            return $this->belongsToMany(Role::class)->withTimestamps();
        }

当然还有数据透视表"role_user" 包含id, user_id, role_id and timestamps

我尝试让用户 ordered By roles name 像这样:

$users = App\Models\User::with('roles')->orderBy('roles.name', 'desc')->get();

但我有这个错误:

Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.name' in 'order clause' (SQL: select * from `users` where `users`.`deleted_at` is null order by `roles`.`name` desc)
http://localhost:8000/users 

请帮忙。

【问题讨论】:

    标签: laravel eloquent-relationship


    【解决方案1】:

    试试这样:

    $users = App\Models\User::with('roles')->get();
    // order of the roles
    $array = ['User','Admin','Doctor', 'Manager']; 
    $sorted = $users->sortBy(function($model) use ($array) {
        return array_search($model['roles'], $array);
    });
    

    希望对你有帮助!

    【讨论】:

    • 那你想要什么?
    • 感谢您的回答,是的,它仅适用于为同一用户订购角色,但我想对所有用户进行排序,然后所有用户都有一个超级角色,然后用户有一个角色的医生然后用户具有管理员角色
    • 这是您回答Imgur 的结果,但我想按角色列排序表格
    • 好的,对于变量 $array 我这样使用它 $array = App\Models\Role::get('name')->toarray();这是正确的吗 ? $market 是什么?
    • 对不起,那是$user弄错了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    相关资源
    最近更新 更多