Laravel 在插入新记录时将数据添加到数据透视表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28274492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:51:36  来源:igfitidea点击:

Laravel adding data to pivot table while inserting new record

laraveleloquent

提问by Dipendra Gurung

I have three tables,

我有三张桌子,

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

In this scenario, I have users table is associated to roles table with many to many relation.

在这种情况下,我将用户表与具有多对多关系的角色表相关联。

I have two eloquent model as

我有两个雄辩的模型

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

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

Now, the question is when I want to add a new user along with ids of roles that I would like to assign to users. How can I insert values to pivot table with Laravel best practices?

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

My existing code is:-

我现有的代码是:-

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

What to do next???

接下来做什么???

采纳答案by lukasgeiter

It's really all described in the documentation.

文档中确实描述了所有内容

Anyway, here's how you do it:

无论如何,这是你的方法:

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

The important part is that you have to save the user before attaching the roles because otherwise the user doesn't have an id yet to be used in the pivot table.

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