Laravel Enloquent按关系表列排序 [英] Laravel Eloquent sort by relation table column

查看:519
本文介绍了Laravel Enloquent按关系表列排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从 shop_products 表中的列从 shop_products_options 表:

$products = Shop\Product::with(['options' => function ($query) {

    $query->orderBy('pinned', 'desc'); 

}])->paginate(5);

我在Shop\Product模型中设置关系:

I set relation in Shop\Product model:

public function options()
{
    return $this->hasOne('Shop\Options');
}

但产品没有排序。我得到的一个查询只适用于 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 = 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 子句是为了不在产品模型中附加加入的列。

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

编辑:as per @alexw comment - 如果需要,您仍然可以包括连接表中的列。您可以将它们添加到选择或调用 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 Enloquent按关系表列排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆