【问题标题】:Laravel collection orderBy relation columnLaravel 集合 orderBy 关系列
【发布时间】:2019-03-19 00:36:57
【问题描述】:

我在 laravel 中有一对多的关系:

  1. 类型
  2. 产品 - type_id、价格

我怎样才能以最低价格获得 $types 的产品订单?

例子:

  • type_1 有:product_x - 10€,product_y - 15€
  • type_2 有:product_a - 20 欧元,product_b - 100 欧元
  • type_3 有:product_e - 12 欧元,product_f - 200 欧元

所以类型应该按顺序排列:type_1、type_3、type_2。

我试过了:

$types = $types->whereHas('products', function($q) use($order_by_price){
            $q->orderBy('price', $order_by_price);
        });

但没用。

我还尝试了 join(),但它以某种方式破坏了集合。可能是因为 types 和 products 表中的列名相同。

Here you got screenshot

【问题讨论】:

  • 您是说产品类型与产品关系是一对多的,那么当产品很多时,您将如何按产品价格订购呢?每种类型需要订购哪种产品?
  • 产品的最低或最高价格。意味着我想按他们的产品最低/最高价格订购 $types。
  • 你可以试试$types->toSql() 获取sql查询吗?
  • select * from types where category_id in (?, ?, ?, ?, ?, ?, ?, ?, ?) 并且存在 (select * from products where @987654327 @.id = products.type_id and price >= ? and price price asc)

标签: php mysql laravel eloquent


【解决方案1】:

做吧

$type->products()->orderBy('price')->get();

Product::orderBy('price')->get();

如果您想要更详细的答案,请分享更多代码(模型、控制器等),以便我知道如何使用不同的模型/解决方案

【讨论】:

  • 但我尝试获取 $types 而不是 $products
【解决方案2】:

由于您有一对多的关系,因此您需要聚合。我发现反过来更容易,即按类型对所有产品进行分组并按最低价格排序。

 $types = Product::with('type')->groupBy('type_id')
         ->select('type_id', \DB::raw('MIN(price) as minPrice'))
         ->orderBy('minPrice')
         ->get()
         ->pluck('type');

这假设您在产品中定义了名为“type”的类型关系。

【讨论】:

  • 是否有可能将 pluck() 函数与 paginate() 一起使用?请查看我的控制器的屏幕截图,以便您了解我需要如何使用它。谢谢你的回答。
  • 好吧,您可以使用paginate(9) 而不是->get()->pluck(),但是在您看来,您需要使用$item->type 来获取页面中每个项目的类型。
  • 我不能这样做,因为在我看来,我正在显示一个 $types 列表,所以我对类型有 foreach。而且你的解决方案是让我得到所有类型,但我只需要某些类别的 $types(屏幕截图 - whereIn 条件)。
【解决方案3】:

首先,您收集所有过滤器并将它们一起应用。您可以执行以下操作。

$min_price = request('min_price');
$max_price = request('max_price');
$order_by_price = request('order_by_price');

$types = Type::whereIn('category_id', $type_categories)->whereHas('products', function ($q) use ($min_price, $max_price, $order_by_price) {
    if (!is_null($min_price)) {
        $q->where('price', '>=', $min_price);
    }

    if (!is_null($max_price)) {
        $q->where('price', '<=', max_price);
    }

    if (!is_null($order_by_price)) {
        $q->orderBy('price', $order_by_price);
    }
})->paginate(9);

【讨论】:

  • 当您没有得到预期的输出时,您可以在构建器上运行-&gt;toSql() 以获取实际查询并根据您的需要进行修改。
  • 这是我用你的代码得到的:select * from types where category_id in (?, ?, ?, ?, ?, ?, ?, ?, ?) 并且存在 ( select * from products where types.id = products.type_id and price >= ? and price price asc)
猜你喜欢
  • 2020-06-02
  • 2013-08-11
  • 1970-01-01
  • 1970-01-01
  • 2020-03-25
  • 2014-08-04
  • 2018-06-06
  • 1970-01-01
  • 2019-08-31
相关资源
最近更新 更多