簡體   English   中英

如何通過急切加載 laravel eloquent 下訂單

[英]How to make order by in eager load laravel eloquent

我想詢問如何通過內部急切加載 laravel eloquent 使用訂單,我已經有這樣的查詢:

$getData = StockIn::select(
        StockIn::raw('group_concat(stock_ins.id_stock_in) as id_stock_ins'), 
        'stock_in_id_type'
    )
    ->with(['type_of_items' => function ($query) {
        $query->orderBy('type_of_item');
    }])
    ->orderBy('type_of_items.type_of_item')
    ->groupBy('stock_ins.stock_in_id_type')
    ->get();

但是當我編譯查詢並查看結果時,我的查詢結果沒有按查詢順序生成結果,我在查詢中是否犯了錯誤以使結果與我的期望相匹配? 之前謝謝

這里是我的 model:

庫存:

public function type_of_items() {
    return $this->belongsTo('App\TypeOfitem', 'stock_in_id_type');
}

物品類型:

public function stock_ins() {
    return $this->hasMany('App\StockIn');
}

當我嘗試在控制台上查看時,我的查詢結果如下:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'type_of_items.type_of_item' in 'order clause' (SQL: select group_concat(stock_ins.id_stock_in) as id_stock_ins, `stock_in_id_type` from `stock_ins` group by `stock_ins`.`stock_in_id_type` order by `type_of_items`.`type_of_item` asc)

您當前正在對預先加載的數據使用 order by。

相反,您需要在 model 本身上調用它。

$getData = StockIn::select(
    StockIn::raw('group_concat(stock_ins.id_stock_in) as id_stock_ins'), 
   'stock_in_id_type'
    )
->with(['type_of_items' => function ($query) {
    $query->orderBy('type_of_item');
}])
->orderBy('type_of_items.type_of_item')
->groupBy('stock_ins.stock_in_id_type')
->get();

您也可以先嘗試不使用 groupBy,以確保獲得正確的結果

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM