我有 2 個模型:
有多種價格的產品型號:
public function prices()
{
return $this->hasMany(Price::class)->orderBy('price', 'DESC');
}
屬于產品的價格模型:
public function product()
{
return $this->belongsTo(Product::class);
}
還有一些其他的關系。我有一個這樣的查詢:
$query = Product::query();
$query->where('brandId', $brand->id);
$query->where('termId', $termId);
$query->when($productType, function ($q) use ($productType){
$q->with('productAttributes')->whereHas('productAttributes', function($query) use ($productType){
$query->where(['attributeId'=> 5, 'attributeDataId'=>$productType]);
});
});
我也想查詢產品價格。
主要問題是我只想檢查第一個價格,看看它是否小于給定的數字。
此查詢檢查所有價格(這不是我想要的):
$query->when($maxPrice, function ($q) use ($maxPrice){
$q->with('prices')->whereHas('prices', function($query) use ($maxPrice){
$query->where('price', '<=', $maxPrice);
});
});
uj5u.com熱心網友回復:
您可以為此使用子查詢 where 子句:
->where(function ($query) {
$query->select('price')
->from('prices')
->whereColumn('products.id', 'prices.product_id')
->orderByDesc('price')
->limit(1);
}, '<=', $maxPrice)
您的查詢將類似于:
$query = Product::query()
->where('brandId', $brand->id)
->where('termId', $termId)
->when($productType, function ($q) use ($productType) {
$q->with('productAttributes')
->whereHas('productAttributes', function ($query) use ($productType) {
$query->where(['attributeId' => 5, 'attributeDataId' => $productType]);
});
})
->when($maxPrice, function ($q) use ($maxPrice) {
$q->with('prices')->where(function ($query) {
$query->select('price')
->from('prices')
->whereColumn('products.id', 'prices.product_id')
->orderByDesc('price')
->limit(1);
}, '<=', $maxPrice);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/370930.html
