违反完整性约束:1452 无法在 Laravel 5.2 中添加或更新子行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36735085/
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
Integrity constraint violation: 1452 Cannot add or update a child row in Laravel 5.2
提问by Chonchol Mahmud
I get an error when i try to insert a role
.I have found some solution of this issue in StackOverFlowbut all those does not solve my problem.
尝试插入时出现错误role
。我在StackOverFlow 中找到了此问题的一些解决方案,但所有这些都不能解决我的问题。
I am trying to get id
from roles
table into roleID
column of user_roles
table.Here i am using Query Builderof Laravel 5.2.
我正在尝试id
从roles
表进入表的roleID
列。user_roles
这里我使用的是 Laravel 5.2 的查询生成器。
public function store(Request $request)
{
//
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$id= $data->id;
DB::table('user_roles')->insert([
'roleID' => $id
]);
//return $data;
return redirect(route('allRole'));
}
When i insert any role then it insert new data in roles
table but i am not getting roleID
in user_roles
table.I get an error:
当我插入任何作用,然后将其插入新的数据roles
表中,但我没有得到roleID
在user_roles
table.I得到一个错误:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`amarjobs`.`user_roles`, CONSTRAINT `fkuserRolesuserID` FOREIGN KEY (`userID`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `user_roles` (`roleID`) values (14))
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`amarjobs`.`user_roles`, CONSTRAINT `fkuserRolesuserID` FOREIGN KEY (`userID`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `user_roles` (`roleID`) values (14))
Where is the problem i have done? Thanks in advanced. Searched result:
我做的问题在哪里?提前致谢。 搜索结果:
回答by Emran
It seems you are trying to insert only roleID
to user_roles
table.
But within in your given error it seems the user_roles
TABLE has also userID
field what is foreign key and connect with users
(id
) table.
看来您只想插入roleID
到user_roles
表中。但是在您给定的错误中,似乎user_roles
TABLE 也userID
字段什么是外键并与users
( id
) 表连接。
As user_roles
is a pivot table and it has both roleID
and userID
and both are foreign key. So while inserting with only roleID
value it's trying to insert the userID
with the NULL value what is not matched with user
Table any of IDs that's why Integrity constraint Violated.
由于user_roles
是透视表和它既有roleID
和userID
无一不是外键。因此,在仅插入roleID
值时,它试图插入userID
与user
表任何 ID不匹配的 NULL 值,这就是违反完整性约束的原因。
So inserting data in a right way would be, you have to provide VALID userID
as well.
因此,以正确的方式插入数据,您还必须提供 VALID userID
。
$id= $data->id;
DB::table('user_roles')->insert([
'roleID' => $id,
'userID' => $EXISTING_USER_ID
]);
I think, it will solve your problem.
我想,它会解决你的问题。
回答by ARIF MAHMUD RANA
As you can see your user_roles
table required userID
column & you aren't passing the field while inserting that's what generating the error.
正如您可以看到您的user_roles
表格所需的userID
列 & 您在插入时没有传递该字段,这就是产生错误的原因。
DB::table('user_roles')->insert([
'roleID' => $id,
'userID' => $userId, //pass your userID here
]);
Also I like to mention couple of things you are naming your DB table column names in camel case which is bad you should be using underscores & as db sqls are generally case insensitive so using userID
is equivalent to userid
.
另外,我想提一下您在驼峰式大小写中命名数据库表列名的几件事,这很糟糕,您应该使用下划线,因为 db sqls 通常不区分大小写,因此使用userID
等效于userid
.
Also you are using DB::insert
it will not insert any created_at
or updated_at
field or other eloquent features so I suggest you insert using eloquent model
& using relations which is the beauty of laravel & eloquent active records
此外,您使用DB::insert
它不会插入任何created_at
或updated_at
字段或其他雄辩的功能,所以我建议您插入 using eloquent model
& using 关系,这是 laravel 和 eloquent 活动记录的美妙之处
try like this
像这样尝试
public function store(Request $request)
{
//
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$userdata = User::all();
$user_id = $userdata->first()->id;
$id= $data->id;
DB::table('permissions')->insert([
'role_id' => $id
]);
DB::table('user_roles')->insert([
'roleID' => $id,
'userID' => $user_id
]);
//return $data;
return redirect(route('allRole'));
}
Here $userdata = User::all();
you are selecting all user do you want all your to have this role then you have to loop through on it & insert it. Or if you want first user to have this role then it's fine.
在这里,$userdata = User::all();
您选择所有用户,您是否希望所有用户都拥有此角色,然后您必须遍历它并插入它。或者,如果您希望第一个用户拥有此角色,那也没关系。
Also I suggest I think you should read more Laravelsdocumentation to clear things.
另外我建议我认为您应该阅读更多Laravel文档来清除问题。
回答by Qazi
in your above error, you are missing the userID
field, which is must in relationship perspective. so you should pass the userID
then your code will be working.
在您的上述错误中,您缺少该userID
字段,这在关系的角度是必须的。所以你应该通过userID
然后你的代码将工作。
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$id= $data->id;
DB::table('user_roles')->insert([
'roleID' => $id,
'userID'=>1, // pass userID with whom you wan to attach new roleID
]);
return redirect(route('allRole'));
here is advance version of using relationship method
这是使用关系方法的高级版本
Add these method in respective models
在各自的模型中添加这些方法
user model
用户模型
public function userRoles(){
return $this->belongsToMany('App\Role','user_roles','userID','roleID');
}
role model
好榜样
public function roleUsers(){
return $this->belongsToMany('App\User','user_roles','roleID', 'userID');
}
and do this for insertion of roles.
并执行此操作以插入角色。
$user = App\User::find(1);
$user->roles()->attach($roleId);
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$id= $data->id;
$user->userRoles()->attach(['
'roleID' => $id,
'userID'=>$user->id
']);
return redirect(route('allRole'));