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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大