我有两个模型,分别叫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的Product应该放在第一位,因为它的最低价格是100。
我试着用产品加入商家,但因为可以有超过1个商家,产品被克隆了。
发布于 2021-05-07 19:32:06
以下是解决方案;)
$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();https://stackoverflow.com/questions/67433732
复制相似问题