gpt4 book ai didi

php - Laravel - 当你有多对多关系时如何查询

转载 作者:行者123 更新时间:2023-11-29 06:11:59 25 4
gpt4 key购买 nike

所以我有两个模型:Product 和 Size。一种产品可能有多种尺寸,一种尺寸可能有许多具有该尺寸的产品。我用 product_size 数据透视表在它们之间建立了很多关系。现在我需要查询所有具有一定尺寸的产品。这是我的代码:

编辑:

    $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('sizes.size', $sizeArray);
}]);

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

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

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

这是我的模型:

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>

这是我当前的代码。除了查询尺寸外,一切正常。它不输出任何错误。但是它不会根据尺寸查询产品。

最佳答案

您需要的是“Querying Relationship Existence”和whereIn() 的组合方法:

$products = Product::whereHas('size', function ($query) {
// In the following line, replace "name" with the appropriate
// field that relates to $request['size'].
$query->whereIn('name', (array)$request['size']);
})->get();

关于php - Laravel - 当你有多对多关系时如何查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37778498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com