Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 拉雷维尔:多对多的订单是多少?_Laravel_Laravel 5.2 - Fatal编程技术网

Laravel 拉雷维尔:多对多的订单是多少?

Laravel 拉雷维尔:多对多的订单是多少?,laravel,laravel-5.2,Laravel,Laravel 5.2,我有桌子 users id username role id name users_role user_id role_id 我有用户列表,我希望能够按用户名和角色id排序,我如何做到这一点 users 1:first 2:second 3:third roles 1:admin 2:customer users_role 1:1 1:2 2:2 3:2 排序可以是按第一个用户角色\u id(或者对于最大角色\u id->如果用户有角色

我有桌子

users
    id
    username

role
    id
    name

users_role
    user_id
    role_id
我有用户列表,我希望能够按用户名和角色id排序,我如何做到这一点

users
1:first
2:second
3:third

roles
1:admin
2:customer

users_role
1:1
1:2
2:2
3:2

排序可以是按第一个用户角色\u id(或者对于最大角色\u id->如果用户有角色1和2,则按2排序)

首先,您需要为两个模型创建关系:用户和角色(我假设我们有三个表:用户角色角色用户

class User extends Model
{
    public function roles() {
        return $this->belongsToMany('\App\Role');
    }
}

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany('\App\User');
    }
}
接下来,通过此查询,您可以获得用户和角色的列表,按用户名ASC和角色id DESC排序

\App\User::with(array('roles' => function($query) {
                            $query->orderBy('role_id', 'DESC');
                        }))
                        ->orderBy('username', 'ASC')
                        ->get();