Laravel – 通过关系筛选

huangapple go评论50阅读模式
英文:

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-&gt;belongsToMany(&#39;App\Models\Price&#39;);
    }

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-&gt;whereHas(&#39;prices&#39;, function ($query) use ($priceMin) {
        $query-&gt;where(&#39;value&#39;, &#39;&gt;=&#39;, $priceMin);
    });

    // Optionally, filter products by maximum price
    if ($priceMax !== null) {
        $query-&gt;whereHas(&#39;prices&#39;, function ($query) use ($priceMax) {
            $query-&gt;where(&#39;value&#39;, &#39;&lt;=&#39;, $priceMax);
        });
    }

    // Retrieve the filtered products
    $filteredProducts = $query-&gt;get();

    return $filteredProducts;
}

Or instead $query=Product::query(), you can call

$products=Product::whereHas(&#39;prices&#39;, function ($query) use ($priceMin) {
        $query-&gt;where(&#39;value&#39;, &#39;&gt;=&#39;, $priceMin);
    }))-&gt;get();

huangapple
  • 本文由 发表于 2023年5月22日 18:29:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76305264.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定