How to order by pivot table data in Laravel's Eloquent ORM

前端 未结 5 681
难免孤独
难免孤独 2020-12-17 11:11

In my Database, I have:

  • tops Table
  • posts Table
  • tops_has_posts Table.

When I retrieve a

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 11:23

    In Laravel 5.6+ (not sure about older versions) it's convenient to use this:

    public function articles()
    {
      return $this->belongsToMany('Article', 'tops_has_posts')->withPivot('range')->orderBy('tops_has_posts.range');
    }
    

    In this case, whenever you will call articles, they will be sorted automaticaly by range property.

提交回复
热议问题