如何获取LARAVEL中的三级关系?

How to obtain three level relationship in LARAVEL?

我有 3 个 table,User、Group 和 GroupUser。我想获取组中添加的用户详细信息(用户 table)。这是我正在关注的表格结构。

user
+--------------+----------------------+
| id    | name      | user_statu      |
+--------------+----------------------+
| 1     | John doe  | ofline          |
+--------------+----------------------+
| 2     | John carry| away            |
+--------------+----------------------+
| 3     | jimn carry| online          |
+--------------+----------------------+
| 4     | adward    | online          |
+--------------+----------------------+


group
+--------------+----------------------+
| id    | title     | status          |
+--------------+----------------------+
| 1     | group1    | actie           |
+--------------+----------------------+
| 2     | group2    | acrive          |
+--------------+----------------------+


group_users
+--------------+-------------------+
| id    | user_id   | group_id     |
+--------------+-------------------+
| 1     | group1    | 1            |
+--------------+-------------------+
| 2     | group2    | 1            |
+--------------+-------------------+ 

Model

Group.php

public function users() {
    return $this->hasMany('App\Models\GroupUser', 'group_id');
}

What i am trying is:

$group = Group::with("users")->where([
                        ['id', '=', $user_id],
                        ['status', '=', 1],
                    ])->first();
$group->users

我得到

"users": [
    {
        "id": 1,
        "user_id": 237,
        "group_id": 1,
        "status": 1,
    },

我也想得到 user name

请指正。谢谢。

我想你想在这里做的是 many-to-many 关系 (https://laravel.com/docs/9.x/eloquent-relationships#many-to-many)

在你的模型中 Group.php:

public function users() {
    return $this->belongsToMany('App\Models\User', 'group_users', 'group_id', 'user_id');
}

然后当您执行 $group->users 时,它将包含模型 User 而不是 GroupUser。您现在可以从这里获取名称。

使用代码:

public function users() {
    return $this->belongsToMany(User::class, 'group_users', 'group_id', 'user_id');
}