dongzai5181 2016-06-10 14:31
浏览 69
已采纳

laravel最新的帖子按类别排序

i have a model setup in Eloquent of a many to many relationship of Pages and Articles. My users have the ability to order these articles per page.

So my question is, can i order the relationship with sync...

 $page->articles()->sync($specificOrderOfArticleIds)

And it sync the relationships in the order of that passed array.

so when i query the page

  $page->articles() // in specified order

It's in the specified order.

Maybe i'm missing something obvious here?

  • 写回答

1条回答 默认 最新

  • dqc3469 2016-06-10 15:55
    关注

    In order to do that, you'll need some kind of column in the pivot table that defines an order. For example, an "order" column on the pivot table could be given a value using:

    $page->articles()->sync([1 => ["order" => 1], 42 => ["order" => 6]]);
    

    Then on the read, you can pass a closure into your query to specify the order be by this column.

    $page = Page::whereId($id)->with(['articles' => function($query) {
        $query->orderBy('pivot.order', 'asc');
    }])->get();
    

    The "pivot" keyword is used in relationship queries to point to the middle table.

    However, you can use the closure ability shown above to order by anything you like, not just the pivot table. Depending on how you define the order, you may not even need the new pivot table column.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集