Laravel belongstomany关系返回一个id而不是一个模型

问题描述 投票:1回答:1

我正在学习laravel, 但我遇到了一个问题,我似乎不能让它正确。我有两个模型。

模型 "组"。

 Schema::create('groups', function (Blueprint $table) {
        $table->increments('id')->unique();
        $table->string('name')->unique();
        $table->text('description')->nullable();
        $table->string('picture')->nullable();
        $table->timestamps();
    });

和模型'用户':

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('email')->unique();
        $table->string('password');
        $table->timestamp('email_verified_at')->nullable();
        $table->timestamps();
        $table->rememberToken();
    });

这些模型应该有一个多对多的关系,所以我已经创建了一个透视表命名为'group_user':

Schema::create('group_user', function (Blueprint $table) {
        $table->increments('id');

        $table->integer('group_id')->unsigned();
        $table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');

        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        $table->timestamps();
    });

接下来我定义了多对多的关系。

在'组'模型中。

 public function members()
{
    return $this->belongsToMany('App\User', 'group_user', 'group_id', 'user_id')->withTimestamps();
}

在 "用户 "模型中。

public function groups() {
    return $this->belongsToMany('App\Group', 'group_user', 'user_id', 'group_id')->withTimestamps();
}

在我的数据库中,我有一个数据透视记录,链接组1和用户1。

+----+----------+---------+------------+------------+
| id | group_id | user_id | created_at | updated_at |
+----+----------+---------+------------+------------+
|  1 |        1 |       1 | NULL       | NULL       |
+----+----------+---------+------------+------------+

到目前为止,一切都很好,但是当我试图打印组1的成员时,......。

@foreach($group->members() as $user)
   <p>{{ $user->first_name }}</p>
@endforeach

我得到这个错误。

Trying to get property 'first_name' of non-object

当我像这样打印用户对象时

 @foreach($group->members() as $user)
   <p>{{ $user }}</p>
@endforeach

我得到的结果是 1这是该会员的用户ID。谁能指出我哪里弄错了?我看了好几个小时,但就是看不出来。先谢谢你!

laravel eloquent
1个回答
1
投票

试试 $group->members 而不是 $group->members(). 因为 $group->members() 返回关系建立者。

© www.soinside.com 2019 - 2024. All rights reserved.