简体   繁体   English

雄辩的 ORM | Laravel 的 hasMany(多于 1)关系

[英]Eloquent ORM | Laravel's hasMany (more than 1) relation

Stackoverflow!堆栈溢出!

I'm usign Laravel.我正在使用 Laravel。 The question is about relations in Eloquent.问题是关于 Eloquent 中的关系。

Item might have 1 or more than 1 types.项目可能有 1 种或 1 种以上。


Item.php:项目.php:

public function types() 
{
    return $this->hasMany('App\Type');
}

Type.php:类型.php:

public function items() 
{
    return $this->belongsToMany('App\Item');
}

Item table:物品表:

id
name

Type table:类型表:

id
name

The question问题

I have 4 types.我有4种类型。 Item №1 has 2 types, Item №2 has 1 type.项目 №1 有 2 种类型,项目 №2 有 1 种类型。 How should I store item types in database?我应该如何在数据库中存储项目类型?

You need to define two belongsToMany() relationships.您需要定义两个belongsToMany()关系。 In the Item model:Item模型中:

public function types() 
{
    return $this->belongsToMany('App\Type');
}

And in the Type model:Type模型中:

public function items() 
{
    return $this->belongsToMany('App\Item');
}

Also, create the item_type pivot table.此外,创建item_type数据透视表。

To work with this many-to-many relationship use the attach() , detach() and sync() methods.要处理这种多对多关系,请使用attach()detach()sync()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM