[英]Laravel integrity constraint violation when saving many to many relationship
When storing a new user and then syncing
some many to many relationships I get an integrity constraint error as the ID of the newly created user seems to not be passed to the sync()
method. 当存储一个新用户,然后
syncing
许多多关系时,由于新创建的用户的ID似乎没有传递给sync()
方法,因此我收到一个完整性约束错误。 Here is my store
controller method: 这是我的
store
控制器方法:
$user = new User;
$user->name = Input::get('name');
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
// See if roles are passed, if not assign the default role of "view_site"
$roles = Input::has('roles') ? Input::get('roles') : [3];
$user->roles()->sync($roles);
As you can see I call save()
before trying to sync
the related data so it should have an ID. 如您所见,在尝试
sync
相关数据之前,我先调用save()
,因此它应该有一个ID。 Here is the error: 这是错误:
Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into
users_roles
(role_id
,user_id
) values (3, ))违反完整性约束:1048列“ user_id”不能为空(SQL:插入到
users_roles
(role_id
,user_id
)值(3,))
If I run the sync method on an already existent user ( User::find($id)->roles()->sync([1,2,3])
) it works fine. 如果我在一个已经存在的用户上运行sync方法(
User::find($id)->roles()->sync([1,2,3])
),它可以正常工作。
For reference, the relationships: 作为参考,这些关系:
// User.php
public function roles()
{
return $this->belongsToMany('Role', 'users_roles');
}
// Role.php
public function users()
{
return $this->belongsToMany('User', 'users_roles');
}
Edit: 编辑:
Query log prior to the sync()
. 在
sync()
之前查询日志。 Looks like the save()
is not writing to the database... 看起来
save()
没有写入数据库...
Array
(
[0] => Array
(
[query] => select * from `users` where `id` = ? limit 1
[bindings] => Array
(
[0] => 1
)
[time] => 0.63
)
[1] => Array
(
[query] => select `roles`.*, `users_roles`.`user_id` as `pivot_user_id`, `users_roles`.`role_id` as `pivot_role_id` from `roles` inner join `users_roles` on `roles`.`id` = `users_roles`.`role_id` where `users_roles`.`user_id` = ?
[bindings] => Array
(
[0] => 1
)
[time] => 0.58
)
[2] => Array
(
[query] => select count(*) as aggregate from `users` where `email` = ? or `username` = ?
[bindings] => Array
(
[0] => test@example.com
[1] => example
)
[time] => 0.48
)
)
Since you are using confide , the validation is based on Ardent . 由于您使用的是confide ,因此验证基于Ardent 。 In your
store
method, add if
statement 在您的
store
方法中,添加if
语句
if($user->save());
$roles = Input::has('roles') ? Input::get('roles') : [3];
$user->roles()->sync($roles);
}else{
return Redirect::back()->withErrors($user->errors());
}
If you don't need to check validation , you may use 如果您不需要检查验证,则可以使用
$user->forceSave();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.