【问题标题】:How to sort by primary table field and pivot in Eloquent?如何在 Eloquent 中按主表字段排序和透视?
【发布时间】:2015-08-13 22:30:48
【问题描述】:

数据透视表有一个额外的字段:排序顺序的序数。如何按序数和浪漫颜色排序?

Inventory::where('item_id', '=', $itemId)
->with('size')
->orderBy('romance_color')
->get();

文档有以下示例:

$users = User::with(array('posts' => function($query)
{
    $query->orderBy('created_at', 'desc');
}))->get();

如何先按主表中的字段排序,然后再按数据透视表字段排序?例如,我可以按用户添加日期排序,然后按帖子创建日期排序吗?

你能在 eloquent 中提出替代解决方案吗?

谢谢

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    我使用了 eloquent 的简单连接:

    Inventory::where('item_id', '=', '170')
    ->with('size', 'color', 'item.category')
    ->join('attribute_value_size_group as gr', 'gr.attribute_value_id', '=', 'size_id')
    ->orderBy('romance_color')
    ->orderBy('ordinal')
    ->select('inventory.*', 'gr.ordinal')
    ->get()->toArray();
    

    【讨论】:

      【解决方案2】:

      您可以使用查询生成器:

      例如:

       $pivotTable= DB::table('pivot_table')->where('item_id', $itemID)->orderBy('romance_color')->get();
      

      【讨论】:

        【解决方案3】:

        试试这个。

        $otherModelCollection = Inventory::where('item_id', '=', $itemId)->otherModel()
        ->orderBy('romance_color')
        ->orderBy('pivot_ordinal')
        ->get();
        

        和这个有点关系。

        http://laravel.io/forum/04-17-2014-order-by-pivot-table-attribute-in-eloquent

        【讨论】:

        猜你喜欢
        • 2012-12-27
        • 2014-12-20
        • 2015-06-21
        • 2018-03-30
        • 1970-01-01
        • 2020-09-05
        • 2018-06-27
        • 1970-01-01
        • 2020-02-25
        相关资源
        最近更新 更多