[英]Laravel Eloquent relation issue for multiple tables
在Laravel 5.5中,我尝试创建一个小型应用程序来管理几个卖家/商店的产品。
因此,我有四个类似的模型:
Seller.php
class Attribute extends Model
{
public function items()
{
return $this->belongsToMany(Item::class);
}
}
Item.php
class Item extends Model
{
public function seller()
{
return $this->belongsTo(Seller::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function attributes()
{
return $this->belongsToMany(Item::class);
}
}
Category.php
class Category extends Model
{
public function items()
{
return $this->hasMany(Item::class);
}
}
Attribute.php
class Attribute extends Model
{
public function items()
{
return $this->belongsToMany(Item::class);
}
}
对于属性和项之间的多对多关系,我创建了一个数据透视表:
Schema::create('attribute_item', function (Blueprint $table) {
$table->integer('attribute_id')->unsigned()->index();
$table->foreign('attribute_id')->references('id')->on('attributes')->onDelete('cascade');
$table->integer('item_id')->unsigned()->index();
$table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
$table->primary(['attribute_id', 'item_id']);
});
整个应用程序的目标是:
我对Laravels关系型方法以及在那种情况下使用哪种方法感到有些困惑。
拥有hasManyThrough
或多态关系可能更好吗?
我必须承认我在这里有一个逻辑问题。 希望你能帮助我。
谢谢!
您可以使用whereHas
方法来查找嵌套关系,以第一个目标为例
从具有属性的类别中提取卖方的所有商品(用于过滤或其他操作)
您可以编写以下内容:
$items = Item::whereHas('seller.items', function ($query) {
$query->whereHas('categories', function ($categories) {
$categories->where('name', '=', 'Mens');
})
->orWhereHas('attributes', function ($attributes) {
$attriutes->where('size', '=', 'large');
});
})->get();
了解有关此的更多信息: https : //laravel.com/docs/5.5/eloquent-relationships#querying-relationship-existence
如果要获取具有类别和属性的项目,这将为您提供项目列表,您可以将其with
method一起使用以获取关系数据:
$items = Item::whereHas('seller.items', function ($query) {
$query->whereHas('categories', function ($caegories) {
$categories->where('name', '=', 'Mens');
})
->orWhereHas('attributes', function ($attributes) {
$atributes->where('size', '=', 'large');
});
})
->with('categories', 'attributes')
->get();
希望这可以指导您所面临的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.