【问题标题】:Laravel adding data to pivot table while inserting new recordLaravel 在插入新记录时将数据添加到数据透视表
【发布时间】:2015-04-01 04:58:37
【问题描述】:

我有三张桌子,

roles(id, name);
users(id, email, password);
user_role(id, user_id, role_id);

在这种情况下,我将 users 表关联到具有多对多关系的角色表。

我有两个雄辩的模型作为

Role
+users(){
    belongsToMany('User')
}

User
+roles(){
    belongsToMany('Role')
}

现在,问题是当我想添加一个新用户以及我想分配给用户的角色 ID 时。如何使用 Laravel 最佳实践将值插入数据透视表?

我现有的代码是:-

$roles = Input::get('roles'); // arrays of role ids

$user = new User();
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();

接下来要做什么???

【问题讨论】:

标签: laravel eloquent pivot-table


【解决方案1】:

真的都是described in the documentation

不管怎样,这就是你的做法:

$user = new User();
$user->username = Input::get('username');
$user->password = Hash::make(Input::get('password'));
$user->save();
$user->roles()->attach($roles);

重要的部分是您必须在附加(使用attach())角色之前保存用户,否则用户没有要在数据透视表中使用的 ID。

【讨论】:

  • 我试过了,但它返回一个错误,调用未定义的方法 Illuminate\\Database\\Eloquent\\Collection::attach()
  • 只是为了澄清,括号很重要! $user->roles()不是$user->roles
  • @lukasgeiter 不太清楚。记录保存后我们怎么知道attach()需要做呢?
  • @surfer190 这就是所有雄辩关系的运作方式。首先你保存一侧,然后关联另一侧。但我同意这在文档中可能不是很清楚。
  • 在 laravel 5.4 中也是如此?
猜你喜欢
  • 2017-05-09
  • 2019-06-12
  • 2014-08-24
  • 1970-01-01
  • 2021-01-29
  • 2016-01-23
  • 2018-11-14
  • 1970-01-01
  • 2023-02-01
相关资源
最近更新 更多