How to sort by a field of the pivot table of a many-to-many relationship in Eloquent ORM

前端 未结 5 835
甜味超标
甜味超标 2020-12-14 15:22

I have been using Eloquent ORM for some time now and I know it quite well, but I can\'t do the following, while it\'s very easy to do in Fluent.

I h

5条回答
  •  醉梦人生
    2020-12-14 16:01

    I have been doing this ( on several builds ) simply using the relationship method as you have. I often use an 'order' column in the pivot table and then do something like this.

    $article->tags()->order_by( 'order')->get();
    

    This may be ambiguous if you have columns named 'order' in the joining table. If so you would need to specify ->order_by( 'article_tag.order' ). And yes, you need to use ->with() to get that column in the result set. As just a matter of style I would leave the with() out of the relationship method and just return the vanilla relationship object instead.

提交回复
热议问题