orderBy()不使用连接的关系

时间:2016-05-17 21:37:00

标签: laravel laravel-5 laravel-5.2

到目前为止,我一直按照模特的关系进行订购:

$users = User::leftJoin('user_stats', 'users.id', '=', 'user_stats.user_id')
    ->orderBy('user_stats.num_followers')
    ->get();

这是User模型:

class User extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'users';

    public function stats()
    {
        return $this->hasOne('App\Models\UserStat');
    }
}

有没有更好的方式orderBy模型的关系而不必使用任何连接?我使用的是Laravel 5.2。

2 个答案:

答案 0 :(得分:0)

您可以改为使用Collection:

$users = User::with('stats')->get()->sortBy(function($user, $key) {
    return $user['stats']['num_followers'];
})->values()->all();

https://laravel.com/docs/5.2/collections#method-sortby

答案 1 :(得分:0)

只要您要订购的列位于不同的表格上(例如,在相关型号上),您就必须加入该表格。

收藏品排序: 愚蠢的提议并没有为你节省加入。在使用连接提取数据后,它仅在php中手动对集合进行排序。

编辑:事实上,with('stats')不会生成任何联接,而是会生成单独的SELECT * FROM user_stats WHERE ID IN (x, y, z, …)。好吧,它实际上为你节省了一个加入。

保留副本 真正保存连接的一种方法是直接在users表中获得num_followers的副本。或者也许只在那里存储,所以你不必保持值同步。