发布于 4年前

Laravel 使用多对多关联中间表 Pivot Table 的字段进行排序

用户可以收藏文章。如何按照用户的收藏时间进行排序?

User 模型中:

public function favorites()
{
    return $this->belongsToMany(Article::class, 'favorites')
                         ->orderBy('favorites.created_at', 'desc')
                         ->withTimestamps();
}

注意上面的 orderBy 语句。

直接读取即是按照中间表排序过的:

$articles = $user->favorites;
©2020 edoou.com   京ICP备16001874号-3