【问题标题】:Laravel belongsToMany only works one wayLaravel belongsToMany 只有一种方式
【发布时间】:2016-04-10 15:37:22
【问题描述】:

我正在尝试建立多对多关系,在此示例中为用户和角色。

在用户模型中我得到了这个:

public function roles()
{
    return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id');
}

在角色模型中我得到了这个:

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

还有我的数据透视表 user_role:

public function up()
    {
        Schema::create('user_role', function(Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->integer('role_id')->unsigned();
            $table->timestamps();

            $table->foreign('role_id')->references('id')->on('roles');
            $table->foreign('user_id')->references('id')->on('users');
        });
    }

现在当我执行$user->roles()->attach(1); 时,它会在 user_role 表中生成一行。但问题是当我想访问它时:$user->roles; 它什么也不返回。它适用于$role->users;,但不适用于其他方式。我做错了什么?

【问题讨论】:

标签: php mysql laravel eloquent pivot-table


【解决方案1】:

已解决:Laravel 5.2.29

确保表名是role_user

    $user = User::find(1);
    $role = Role::find(2);
    // In this example I am passing in a Role object but $role->id also works
    $user->roles()->attach($role);

希望这对你有用。

【讨论】:

  • 我尝试了两个表名 user_role 和 role_user 但仍然是同样的问题。 belongsToMany('App\User', 'user_role', 'role_id', 'user_id'); 在这第二个参数表示表名,第三个表示当前模型行,第四个表示附加模型行名
  • 我已经为你创建了 repo。克隆以下仓库:https://github.com/HashmatWaziri/laravel-5.2.29-manyToManyRelationship
【解决方案2】:

你必须像这样附加后重新加载关系

$user->roles()->attach($role);

$user->load('roles');

【讨论】:

    猜你喜欢
    • 2019-08-30
    • 2016-08-15
    • 1970-01-01
    • 2017-10-04
    • 2021-08-30
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多