【问题标题】:LARAVEL - how to retrieve data from three tables connected through two pivot tablesLARAVEL - 如何从通过两个数据透视表连接的三个表中检索数据
【发布时间】:2020-01-23 06:57:56
【问题描述】:

以下是三个表格:

1.用户(ID、姓名)

2.屏幕(id、名称)

3.列(id、名称)

screen 和 column 通过枢轴连接:

column_screen(id,column_id,screen_id)

和 column_screen 和 user 通过枢轴连接:

column_screen_user(id,column_screen_id,user_id)

现在如何通过 eloquent 关系检索 user 即 'abc' 及其 screen 名称及其 columns 名称?

喜欢

{
    "id": 1,
    "name": "user1",
    "screens": [
        {
            "id": 1,
            "name": "screen1",
            "columns": [
                {
                    "id": 1,
                    "name": "column1"
                },
                {
                    "id": 2,
                    "name": "column2"
                }
            ]
        }
    ]
}

【问题讨论】:

  • @Latheesan 请详细说明,“如何”
  • 如果您已经在模型上定义了关系(因此用户 -> 屏幕和屏幕 -> 列),您可以将它们急切地加载到您的控制器中并形成响应。

标签: php laravel eloquent


【解决方案1】:

你需要先建立关系:

用户.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;
}

屏幕.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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多