以下是三个表:
1. 用户(ID,名称)
2. 屏幕(ID,名称)
3. 列(编号,名称)
屏幕和列通过枢轴连接:
column_screen (id,column_id,screen_id)
和 column_screen 和用户通过枢轴连接:
column_screen_user (id,column_screen_id,user_id)
现在如何通过雄辩的关系检索用户,即'abc'及其屏幕名称及其列名称?
喜欢
{
"id": 1,
"name": "user1",
"screens": [
{
"id": 1,
"name": "screen1",
"columns": [
{
"id": 1,
"name": "column1"
},
{
"id": 2,
"name": "column2"
}
]
}
]
}
答案 0 :(得分:0)
您需要先建立关系:
User.php
public function screens() {
return $this->hasMany('App\Screen');
}
// you can also build shortcuts through your relationships
public function columns() {
$columns = [];
foreach ($this->screens as $screen) {
$columns[] = $screen->columns();
}
return $columns;
}
Screen.php
public function columns() {
return $this->hasMany('App\Columns');
}
在您的控制器中/任何需要的地方:
$user = User::find(42);
$screens = $user->screens();
foreach ($screens as $screen) {
// you can access like: $screen->columns();
}
// or using the shortcut
$columns = $user->columns();