我的应用中有多级关联
Category
|products
|product_items
|product_group
|product_attributes
类别模型
public function products(){
return $this->belongsToMany(Product::class);
}
产品型号
public function items()
{
return $this->hasMany(ProductItem2::class);
}
项目模型
public function attribute()
{
return $this->belongsToMany(AttributeValue::class,'product_groups','item_id','attribute_id')->withTimestamps();
}
属性值
public function attributeName(){
return $this->belongsTo(Attribute::class,'attribute_id');
}
所有关系都很好,但现在我需要通过示例'颜色'过滤产品
所以我尝试了
return $this->where('parent_id',0)->whereHas('childrenRecursive')->with('products.items.attribute.attributeName')->get();
当然,它返回所有类别以及所有产品和产品项等
这是迁移文件
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('image');
$table->string('cover')->nullable();
$table->string('url')->nullable();
$table->string('cover');
$table->text('url_cover');
$table->text('description')->nullabel();
$table->unsignedInteger('parent_id');
$table->boolean('elite')->default(0);
$table->timestamps();
});
Schema::create('category_product',function (Blueprint $table){
$table->integer('category_id');
$table->integer('product_id');
$table->primary(['product_id','category_id']);
});
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->string('serial_number');
$table->float('price');
$table->integer('discount');
$table->enum('type',['pound','percentage']);
$table->timestamp('start')->nullable();
$table->timestamp('end')->nullable();
$table->string('image');
$table->unsignedInteger('shop_id');
$table->boolean('recommendation');
$table->boolean('published');
$table->integer('preparing_days')->unsigned();
$table->integer('visits')->defualt(0);
$table->unsignedInteger('priorty')->defualt(0);
$table->timestamps();
});
Schema::create('product_items', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('product_id');
$table->double('price');
$table->string('image');
$table->unsignedInteger('amount');
$table->timestamps();
});
Schema::create('product_groups', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('attribute_id');
$table->unsignedInteger('item_id');
$table->timestamps();
});
Schema::create('attribute_values', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('attribute_id');
$table->string('value');
$table->timestamps();
});
Schema::create('attributes', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
我所有需要返回的属性'color'值(如['red,blue,black']
)与每个类别
似乎很复杂,需要帮助。