如何根据尺寸查询产品?

时间:2016-06-13 11:34:45

标签: php mysql database laravel eloquent

所以我有型号产品,必须按颜色,价格和尺寸进行过滤。这是我的关系。

class Product extends Model
{
    public function color()
    {
        return $this->belongsTo('App\Color');
    }

    public function sizes()
    {
        return $this->belongsToMany('App\Size', 'product_size')->withTimestamps();
    }
}

这是我的尺寸模型:

class Size extends Model
{
    public function products()
    {
        return $this->belongsToMany('App\Product', 'product_size')->withTimestamps();
    }
}

这是我的表格:

<form id="filterOptions" method="get" action="{{ URL::current() }}">
    <button type="submit" class="btn-color">Filter</button>

    <div class="clearfix space20"></div>
    <h5>Color</h5>
    <ul class="color-list">
        @foreach($availableColors as $color)
            <li><input type="checkbox" name="color[]" value="{{ $color->id }}"><a href="#"><span class="{{ $color->name }}"></span> {{$color->name_bg}}</a></li>
            {{ $color->name }}
        @endforeach
    </ul>
    <div class="clearfix space20"></div>

    <h5>Price</h5>
    <div id="slider-container"></div>
    <p>
        <span class="{{--pull-right--}} sc-range">
            <input class="pull-left" name="min" type="text" id="min" style="border: 0; color: #333333; font-weight: bold;"/>
            <input class="pull-right" name="max" type="text" id="max" style="border: 0; color: #333333; font-weight: bold;"/>
        </span>
    </p>

    <div class="clearfix space30"></div>
    <h5>Size</h5>
    <ul class="size-list">
        @foreach($availableSizes as $size)
            <li><input type="checkbox" name="size[]" value="{{ $size->id }}">{{ $size->size }}</li>
        @endforeach
    </ul>
</form>

我设法按价格和颜色查询产品而没有任何问题。但是,当它是多对多的关系时,我无法让它进行查询。我怎样才能做到这一点?到目前为止,这是我的代码:

$minPrice = $request['min'];
$maxPrice = $request['max'];
$colors = $request['color'];
$sizes = $request['size'];

if (count($request->all()) != 0) {
    $query = Product::with(['sizes' => function($query) use($request) {
        $sizeArray = $request->get('size');
        $query->whereIn('size', $sizeArray);
    }]);

    if(isset($minPrice) && isset($maxPrice)) {
        $query->whereBetween('price', array($minPrice, $maxPrice));
    }

    if(isset($colors)) {
        $query->whereIn('color_id', $colors);
    }

    $products = $query->get();
}

除了尺寸查询之外,一切都有效。我怎样才能解决这个问题?拜托,我无法找到解决方案。

0 个答案:

没有答案