Laravel 在插入新记录时将数据添加到数据透视表 [英] Laravel adding data to pivot table while inserting new record

查看:22
本文介绍了Laravel 在插入新记录时将数据添加到数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三张桌子,

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.

我有两个雄辩的模型

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

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

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

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?

我现有的代码是:-

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

接下来要做什么???

推荐答案

其实就是这样 在文档中描述.

无论如何,这就是你的做法:

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

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

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

这篇关于Laravel 在插入新记录时将数据添加到数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆