首页 > 解决方案 > 使用关系列订购主模型

问题描述

我有两个名为Product和的模型Merchant

Product 包含一个产品的基本数据,Product 可以有多个 Merchants。

商家包含每个产品的定价、SKU 等。

现在我想根据第一个商家价格订购产品。

商家总是先按最低价格订购每种产品。

Product::with('merchants')
->whereHas('category', function ($q) use ($highlight) {
    $q->where('id', $highlight->category_id);
})
->orderBy('merchants.price', 'asc')
->get();

例如,这是上述查询的输出,没有使用orderBy.

array:2 [▼
  0 => array:3 [▼
    "id" => 2
    "name" => "Product Name"
    "merchants" => array:1 [▼
      0 => array:1 [▼
        "price" => 4756
      ]
    ]
  ]
  1 => array:3 [▼
    "id" => 3
    "name" => "Another Product"
    "merchants" => array:2 [▼
      0 => array:1 [▼
        "price" => 100
      ]
      1 => array:1 [▼
        "price" => 200
      ]
    ]
  ]

现在我怎样才能根据 First Merchant 价格订购产品?例如,ID 为 3 的产品应该排在第一位,因为它的最低价格为 100。

我尝试通过产品加入商家,但由于可能有超过 1 个商家,产品会自行克隆。

标签: laraveleloquent

解决方案


这是解决方案;)

$products = Product::with('merchants')
    ->whereHas('category', fn ($q) => $q->where('id', $highlight->category_id))
    ->select('products.*')
    ->join('merchants', 'merchants.product_id', '=', 'products.id')
    ->groupBy('products.id')
    ->orderByRaw('MIN(merchants.price)')
    ->get();

推荐阅读