违反完整性约束: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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:38:35  来源:igfitidea点击:

Integrity constraint violation: 1452 Cannot add or update a child row in Laravel 5.2

phpmysqlsql-serverlaravellaravel-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 idfrom rolestable into roleIDcolumn of user_rolestable.Here i am using Query Builderof Laravel 5.2.

我正在尝试idroles表进入表的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 rolestable but i am not getting roleIDin user_rolestable.I get an error:

当我插入任何作用,然后将其插入新的数据roles表中,但我没有得到roleIDuser_rolestable.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:

我做的问题在哪里?提前致谢。 搜索结果:

1.First Solution.2.Second Solution.

1.第一个解决方案。2.第二种解决方案。

回答by Emran

It seems you are trying to insert only roleIDto user_rolestable. But within in your given error it seems the user_rolesTABLE has also userIDfield what is foreign key and connect with users(id) table.

看来您只想插入roleIDuser_roles表中。但是在您给定的错误中,似乎user_rolesTABLE 也userID字段什么是外键并与users( id) 表连接。

As user_rolesis a pivot table and it has both roleIDand userIDand both are foreign key. So while inserting with only roleIDvalue it's trying to insert the userIDwith the NULL value what is not matched with userTable any of IDs that's why Integrity constraint Violated.

由于user_roles是透视表和它既有roleIDuserID无一不是外键。因此,在仅插入roleID值时,它试图插入userIDuser表任何 ID不匹配的 NULL 值,这就是违反完整性约束的原因。

So inserting data in a right way would be, you have to provide VALID userIDas 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_rolestable required userIDcolumn & 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 userIDis equivalent to userid.

另外,我想提一下您在驼峰式大小写中命名数据库表列名的几件事,这很糟糕,您应该使用下划线,因为 db sqls 通常不区分大小写,因此使用userID等效于userid.

Also you are using DB::insertit will not insert any created_ator updated_atfield 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_atupdated_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 userIDfield, which is must in relationship perspective. so you should pass the userIDthen 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'));