2016-11-15 52 views
1

我有一个orderBy在更复杂的查询中的问题。Laravel - 如何订购通过枢轴和每个功能的雄辩查询

我想从指定的俱乐部获得10个有序用户(带有俱乐部的枢轴)并隐藏一些列。

所以我有在几乎为我工作的雄辩查询。问题是通过一些变量(level或exp - 现在还不知道)订购用户

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

 $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; 

我的一个试验(与排序依据):

// 
//  $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; 

错误:

The Response content must be a string or object implementing __toString(), "boolean" given.

我在我的模型中添加了属性。这个属性不能被选中,因为它们不包含在select中,所以它们基本上总是被选中。

我想创建雄辩的查询,这将限制属性只有少数,这让我感兴趣。

回答

0

好吧,我弄明白在不同的办法。也许它看起来不太好,但它的工作原理。比没有隐藏属性的工作速度快得多。

我在我的模型中使用附加属性,它们总是被选中(即使没有选择它们),所以我不得不创建具有我感兴趣的属性的数组。

$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; 

谢谢你们的线索。

1

可以作为尝试:

$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; 
+0

是的,但我有隐藏一些属性的问题。在模型中,我有很多附加属性选择总是显示。每个函数都不会使用这个查询:' - > each(function($ row){0} { 'phone','bio','active','book_transfer_type','email','password','remember_token','created_at','updated_at','active_club','facebook_id','password_token','points ','password_status','pivot']); });' –

+0

检查更新的答案。 –