将多个范围应用于Laravel模型而不会覆盖[5.6]

时间:2018-03-22 07:46:20

标签: php laravel laravel-5.6

我想使用以下条件过滤商店模型,包括目标,价格和产品等过滤器:

  • 所有这些都允许多项选择,所以我总是要传递数组。
  • 我总是必须使用 AND运算符。如果我尝试按price = $和target = men进行过滤,则查询应该类似于'WHERE price_range = $ AND target = men'。

当我尝试进行过滤时,查询始终返回错误的结果。例如,我有一个price_range = $和target = men的商店。当我按price_range = $和target = women进行过滤时,该商店会显示在结果上,这是错误的。

这是我的商店模式

<?php

namespace App;

class Store extends Model
{
    public function values()
    {
        return $this->belongsToMany('App\Value');
    }

    public function targets()
    {
        return $this->belongsToMany('App\Target');
    }

    public function products()
    {
        return $this->belongsToMany('App\Product');
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopePrices($query, $priceRanges = [])
    {
        if ($priceRanges) {
            return $query->whereIn('price_range', $priceRanges);
        }
    }

    public function scopeValues($query, $values = [])
    {
        if ($values) {
            return $query->whereHas('values', function ($query) use ($values) {
                $query->whereIn('name', $values);
            });
        }
    }

    public function scopeTargets($query, $targets = [])
    {
        if ($targets) {
            return $query->whereHas('targets', function ($query) use ($targets) {
                $query->whereIn('name', $targets);
            });
        }


    }

    public function scopeProducts($query, $products = [])
    {
        if ($products) {
            return $query->whereHas('products', function ($query) use ($products) {
                $query->whereIn('name', $products);
            });
        }
    }

}

这是来自StoresController的 getStores()

 public function getStores()
    {
        $stores = Store::active()
            ->prices(request('price_ranges'))
            ->values(request('values'))
            ->targets(request('targets'))
            ->products(request('products'))
            ->orderBy('name')
            ->get();

        return response()->json($stores);
    }

我想用范围来做这个,因为我觉得这是一个干净的方法。提前感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

我认为您已在作用域中将 $ priceranges 定义为数组<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="name-field" class="name-field row"> <div class="col-xs-12 col-sm-6 childname"> <div class="field text-left"> <label class="text-left">Name of child</label> <input id="firstname" class="firstname" name="firstname" type="text" /> </div> </div> <div class="col-xs-12 col-sm-6 dateofbirth"> <div class="field text-left"> <label class="text-left">Date of birth</label> <input type="text" class="date" id="thedate" name="date" /> </div> </div> </div> <a href="#" id="stepname" class="btn">Next Step</a>

只需将$priceRanges = []等所有数组替换为$priceRanges = [],我猜就可以了。因为在定义范围时,不需要定义$priceRanges

例如

$priceRanges = []

请阅读此文档Laravel query scope