如果一个用户可以有许多英雄,而一个英雄也可以属于许多用户,则这是一个多对多关系。在Laravel中,多对多关系的倒数也是多对多关系,它们都由描述belongsToMany()
。
https://laravel.com/docs/5.2/eloquent-relationships#many-to-many
因此,在您的用户模型中:
public function heros() {
return $this->belongsToMany(Hero::class);
}
在英雄模型中:
public function users() {
return $this->belongsToMany(User::class);
}
Laravel将假定联接表名为hero_user
,两个模型名称(单数)按字母顺序联接。如果要user_heroes
像在图像中一样使用,则需要指定它:
return $this->belongsToMany(Hero::class, 'user_heroes');
(在两种模型方法中)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句