簡體   English   中英

Laravel 所屬關系返回一個 id 而不是 model

[英]Laravel belongstomany relationship returns an id instead of a model

我正在學習 laravel,但我遇到了一個問題,我似乎無法正確解決。 我有兩個模型:

Model“組”:

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

和 model '用戶':

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”的 pivot 表:

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();
    });

接下來我定義了多對多關系:

在“組”model 中:

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

在“用戶”model 中:

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

在我的數據庫中,我有一個 pivot 記錄,它將組 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

當我像這樣打印用戶 object

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

我得到結果1 ,這是成員的 user_id。 誰能指出我在哪里搞砸了? 看了好幾個小時,還是看不出來。 提前致謝!

嘗試$group->members而不是$group->members() 因為$group->members()返回關系構建器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM