Laravel Eloquent sort by relation table column

前端 未结 2 701
一生所求
一生所求 2020-11-30 22:59

I tried to sort products from shop_products table by pinned column from shop_products_options table:

$products = Shop\         


        
2条回答
  •  伪装坚强ぢ
    2020-11-30 23:33

    Eager loading uses separate queries so you need join for this:

    $products = Shop\Product::join('shop_products_options as po', 'po.product_id', '=', 'products.id')
       ->orderBy('po.pinned', 'desc')
       ->select('products.*')       // just to avoid fetching anything from joined table
       ->with('options')         // if you need options data anyway
       ->paginate(5);
    

    SELECT clause is there in order to not appending joined columns to your Product model.


    edit: as per @alexw comment - you still can include columns from joined tables if you need them. You can add them to select or call addSelect/selectRaw etc.

提交回复
热议问题