英文:
Laravel - filter through relationship
问题
I have Product and Prices models, so that Product can have multiple prices. It is 'one to many' relation. I need to filter products by min and max price. When there will be price-min value in request, it will show only those products that all its prices are >= price-min.
How can I build a query for that?
英文:
So, I have Product and Prices models, so that Product can have multiple prices. It is 'one to many' relation. I need to filter products by min and max price. When there will be price-min value in request, it will show only those products that all its prices are >= price-min.
How can I build a query for that?
答案1
得分: 2
在模型 Product 中创建关系:
public function prices()
{
return $this->belongsToMany('App\Models\Price');
}
在您的控制器中添加以下内容:
use App\Models\Product;
use App\Models\Price;
function filterProductsByPrice($priceMin, $priceMax = null)
{
$query = Product::query();
// 按最低价格筛选产品
$query->whereHas('prices', function ($query) use ($priceMin) {
$query->where('value', '>=', $priceMin);
});
// 可选地,按最高价格筛选产品
if ($priceMax !== null) {
$query->whereHas('prices', function ($query) use ($priceMax) {
$query->where('value', '<=', $priceMax);
});
}
// 检索筛选后的产品
$filteredProducts = $query->get();
return $filteredProducts;
}
或者,您可以使用以下方式代替 $query=Product::query()
:
$products = Product::whereHas('prices', function ($query) use ($priceMin) {
$query->where('value', '>=', $priceMin);
})->get();
英文:
In model Product create relationship
public function prices()
{
return $this->belongsToMany('App\Models\Price');
}
In your controller add this:
use App\Models\Product;
use App\Models\Price;
function filterProductsByPrice($priceMin, $priceMax = null)
{
$query = Product::query();
// Filter products by minimum price
$query->whereHas('prices', function ($query) use ($priceMin) {
$query->where('value', '>=', $priceMin);
});
// Optionally, filter products by maximum price
if ($priceMax !== null) {
$query->whereHas('prices', function ($query) use ($priceMax) {
$query->where('value', '<=', $priceMax);
});
}
// Retrieve the filtered products
$filteredProducts = $query->get();
return $filteredProducts;
}
Or instead $query=Product::query(), you can call
$products=Product::whereHas('prices', function ($query) use ($priceMin) {
$query->where('value', '>=', $priceMin);
}))->get();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论