如何使用枢轴和每个函数来排序雄辩的查询


Laravel - How to orderBy eloquent query with pivot and each function

我在更复杂的查询中有一个order问题。

我想从指定的俱乐部得到10个有序的用户(pivot with club),并隐藏一些列。

所以我在雄辩中有疑问,这对我来说几乎有效。问题在于对用户按一些变量排序(级别或经验-还不知道)。

我的查询(工作-不排序):

        $users = Club::find($club_id)->users->each(function($row) {
            $row->setHidden(['history', 'books', 'reviews', 'exp', 'erudion_id', 'phone', 'bio', 'active', 'book_transfer_type', 'email', 'password', 'remember_token', 'created_at', 'updated_at', 'active_club', 'facebook_id', 'password_token', 'points', 'password_status', 'pivot']);
        })->take(10);
    return $users;

我的一个试验(使用OrderBy):

    //
//        $users = Club::find($club_id)->with(['users' => function ($q) {
//
//            $q->orderBy('id');
//
//        }])->each(function($row) {
//
//            $row->setHidden(['history', 'books', 'reviews', 'exp', 'erudion_id', 'phone', 'bio', 'active', 'book_transfer_type', 'email', 'password', 'remember_token', 'created_at', 'updated_at', 'active_club', 'facebook_id', 'password_token', 'points', 'password_status', 'pivot']);
//
//        });
//
//        return $users;
错误:

响应内容必须是一个字符串或对象实现__toString(), "boolean"给定。

我在模型中添加了属性。这些属性不能通过在select中不包含它们来取消选择,所以它们基本上总是被选中的。

我想创建一个雄辩的查询,这将限制属性只有几个,这是我感兴趣的。

您可以尝试:

$users = Club::where('id', $club_id)
                ->first()
                ->users()
                ->select('id', 'name') // you can add more columns which you want to select
                ->orderBy('id')
                ->get()
return $users;

或者如果你想使用each,那么你可以这样做:

$users = Club::where('id', $club_id)
                ->first()
                ->users()
                ->orderBy('id')
                ->get()
                ->each(function($user) {
                    $user->setHidden(['history', 'books', 'reviews', 'exp', 'erudion_id', 'phone', 'bio', 'active', 'book_transfer_type', 'email', 'password', 'remember_token', 'created_at', 'updated_at', 'active_club', 'facebook_id', 'password_token', 'points', 'password_status', 'pivot']);
                });
return $users;

好吧,我有另一种方法。也许它看起来不太好,但它很有效。

我在我的模型中使用附加属性,这些属性总是被选中的(即使在eloquent中没有选择它们),所以我必须创建一个包含我感兴趣的属性的数组。

  $users = Club::where('id', $club_id)->first()->users()->orderBy('id')->limit(10)->get();
    $ranking = [];
    foreach($users as $k => $user){
        $ranking[$k]['id'] = $user['id'];
        $ranking[$k]['f_name'] = $user['f_name'];
        ...
    }
    return $ranking;

谢谢大家的提示