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

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

问题描述

我有三个桌子,

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

在这种情况下,我使users表与具有多对多关系的角色表相关联.

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

重要的是,您必须在附加用户之前保存用户(使用

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天全站免登陆