[英]Laravel order a relation by method on the model
嘗試思考從我的API獲取我所需要的替代方法。
我正在使用Laravel Spark並按以下方式進行查詢:
$team = Team::with('users')->find($id);
團隊模型上的用戶關系為:
public function users()
{
return $this->belongsToMany(
'App\User', 'team_users', 'team_id', 'user_id'
)->withPivot('role')->orderBy('current_active_team', 'DESC');
}
我目前正在通過用戶表上的字段對此進行排序,但我也想通過用戶模型上的方法進行排序:
public function queueLength()
{
// returns an integer for the users queue length
}
要返回此數據,我目前正在查詢中添加此數據:
foreach ($team->users as $user) {
$user->queueLength = $user->queueLength();
}
有什么辦法可以按他們的queueLength命令$ team-> users?
一種解決方案是使用collection sortBy
。
首先將queueLength作為屬性。
public function getQueueLengthAttribute()
{
// returns an integer for the users queue length
}
然后使用集合sortBy
$team->users->sortBy('queueLength');
PS:如果您有大量數據或使用分頁,這將不是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.