問題描述
我嘗試通過 shop_products_options
表中的 pinned
列對 shop_products
表中的產品進行排序:
I tried to sort products from shop_products
table by pinned
column from shop_products_options
table:
$products = ShopProduct::with(['options' => function ($query) {
$query->orderBy('pinned', 'desc');
}])->paginate(5);
我在 ShopProduct 模型中設置了關系:
I set relation in ShopProduct model:
public function options()
{
return $this->hasOne('ShopOptions');
}
但是產品沒有排序.我得到一個僅適用于 shop_products_options
表的查詢.
But products aren't sorted. I get a query that only works with shop_products_options
table.
SELECT * FROM `shop_products_options` WHERE `shop_products_options`.`product_id` in ('8', '9', '10', '11', '12') ORDER BY `pinned` DESC
如何解決?
推薦答案
急切加載使用單獨的查詢,因此您需要加入:
Eager loading uses separate queries so you need join for this:
$products = ShopProduct::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
子句是為了不將連接的列附加到您的 Product
模型中.
SELECT
clause is there in order to not appending joined columns to your Product
model.
根據@alexw 評論 - 如果需要,您仍然可以包含連接表中的列.您可以將它們添加到 select
或調用 addSelect/selectRaw
等
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.
這篇關于Laravel Eloquent 按關系表列排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!