当存储新用户然后syncing
一些多对多关系时,我得到完整性约束错误,因为新创建的用户的ID似乎没有传递给sync()
方法。这是我的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);
正如您所见,我在尝试save()
相关数据之前调用了sync
,因此它应该有一个ID。这是错误:
完整性约束违规:1048列' user_id'不能为空 (SQL:插入
users_roles
(role_id
,user_id
)值(3,))
如果我在已存在的用户(User::find($id)->roles()->sync([1,2,3])
)上运行同步方法,它可以正常工作。
供参考,关系:
// User.php
public function roles()
{
return $this->belongsToMany('Role', 'users_roles');
}
// Role.php
public function users()
{
return $this->belongsToMany('User', 'users_roles');
}
修改
在sync()
之前查询日志。看起来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
)
)