LARAVEL-如何从通过两个数据透视表连接的三个表中检索数据

时间:2019-09-23 08:30:28

标签: php laravel eloquent

以下是三个表:

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"
                }
            ]
        }
    ]
}

1 个答案:

答案 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();