我有3个表:用户,语言和级别。
一个用户拥有多种语言和级别。
示例:
表用户
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
| lastname | varchar(50) | NO | | NULL | |
+----------+-------------+------+-----+---------+----------------+
表格语言
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
表级
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
+-------+-------------+------+-----+---------+----------------+
数据透视表
+-------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | NO | | NULL | |
| language_id | int(11) | NO | | NULL | |
| level_id | int(11) | NO | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+-------------+----------+------+-----+---------+----------------+
问题是,如何使用三个表创建具有三个表的数据透视表(在文档层中,该示例仅包含2个表)? 如何与雄辩的关系?
答案 0 :(得分:2)
我在一个项目中有一些东西,使用三个表和枢轴,所以我运行:
Modelo User:
class User extends Model{
public function levels(){
return $this->belongsToMany('App\Level','name pivot table')->withPivot('language_id');
}
public function languages(){
return $this->belongsToMany('App\Language','name pivot table')->withPivot('level_id');
}
}
Modelo Levels:
class Level extends Model{
public function users(){
return $this->belongsToMany('App\User','name pivot table')->withPivot('language_id');
}
public function languages(){
return $this->belongsToMany('App\Language','name pivot table')->withPivot('user_id');
}
}
表语言:
class Language extends Model{
public function users(){
return $this->belongsToMany('App\User','name pivot table')->withPivot('level_id');
}
public function levels(){
return $this->belongsToMany('App\Level','name pivot table')->withPivot('user_id');
}
}
我希望您提供此选项,用于访问所有三个表中的信息
使用:
$user = User::find(1);
$user->levels->pivot->language_id;
$user->levels->name;
$user->languages->pivot->level_id;
$user->languages->name;
答案 1 :(得分:0)
您没有发布您的关系,但您可以创建一个单独的数据透视表模型。因此,您可以在该枢轴模型中定义与用户模型,语言模型和级别模型的关系。