laravel - 使用关系列订购主模型
问题描述
我有两个名为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 个商家,产品会自行克隆。
解决方案
这是解决方案;)
$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();
推荐阅读
- java - Comparator.nullsLast 不避免 NullPointerException
- amazon-web-services - 使用带有 S3 触发器的 Lambda 函数无法写入 DynamoDB
- vb.net - 关于如何集成代码块的任何提示
- java - 什么是事务边界?
- flutter - Flutter 中的 OnStateChanged 方法
- angular - 在离子中掩盖字符串
- javascript - 如何在 google-protobufjs 中设置枚举值
- javascript - 使用 html2canvas.js 将大量数据下载为图像时出现“失败 - 网络错误”
- java - 如何收听将新文件添加到文件夹以显示在 JTable 中?
- ios - 如何知道女巫价值以显示 Apple 订阅的介绍价格或正常价格