我有3张桌子:
products
productcolors
productbrands
他们之间的关系是:
product
有很多productcolors
; productbrands
属于product
。所有products
都标有此依赖关系:cviebrock/eloquent-taggable
。
我用它来渲染所有游泳标记数据:
$allproducts = Product::withAllTags('swim')->get();
现在,我想用颜色和品牌过滤数据,但我不知道该怎么做。
这是我的产品型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentTaggable\Taggable;
use Carbon\Carbon;
class Product extends Model
{
use Taggable;
protected $table ='products';
protected $dates = ['published_at'];
public function setPublishedAtAttribute($date) {
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date);
}
public function scopePublished($query) {
$query->where('published_at', '<=', Carbon::now());
}
public function scopeUnpublished($query) {
$query->where('published_at', '>', Carbon::now());
}
public function scopeNewin($query) {
$query->where('published_at', '>', Carbon::now()->subDays(7));
}
public function getCreatedAtAttribute($date) {
return $this->asDateTime($date)->toFormattedDateString();
}
public function getproductcolor() {
return $this->hasMany('App\productcolor');
}
public function getproductimage() {
return $this->hasMany('App\productimage');
}
public function getproductbrand() {
return $this->hasMany('App\productbrand');
}
public function getproductsize() {
return $this->hasMany('App\size');
}
}
这是我的productcolor
模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentTaggable\Taggable;
class productcolor extends Model
{
use Taggable;
public function getproductcolor() {
return $this->belongsTo('App\Product');
}
}
这是我的productBrands
模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentTaggable\Taggable;
class productbrand extends Model
{
use Taggable;
public function productBrand() {
return $this->belongsTo('App\Product');
}
}
答案 0 :(得分:1)
使用whereHas
和orWhereHas
$allproducts = Product::whereHas('productColors', function($query) {
$query->where('column', 'condition', 'value');
})->withAllTags('swim')->get();
答案 1 :(得分:0)
试试这个:
$allproducts = Product::withAllTags('swim')->with(['getproductcolor' => function ($productColorQuery) {
$productColorQuery->where('blah', '=', 'blah');
}, 'getproductbrand' => function ($productBrandQuery) => {
$productBrandQuery->where('blah', '=', 'blah');
}])->get();
答案 2 :(得分:0)
使用whereHas()
:
Product::whereHas('colors', function ($q) use ($colorName) {
$q->where('name', $colorName);
})
whereHas('brands', function ($q) use ($brandName) {
$q->where('name', $brandName);
})
->withAllTags('swim')
->get();
不要忘记在产品型号中定义关系:
public function colors()
{
return $this->hasMany(Color::class);
}
public function brands()
{
return $this->hasMany(Brand::class);
}