保存多对多关系时,Laravel完整性约束违规

时间:2014-06-05 16:20:06

标签: php laravel laravel-4

当存储新用户然后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_rolesrole_iduser_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
        )

)

1 个答案:

答案 0 :(得分:3)

由于您使用的是confide,因此验证基于Ardent。 在store方法中,添加if语句

if($user->save());
    $roles = Input::has('roles') ? Input::get('roles') : [3];
    $user->roles()->sync($roles);
}else{
    return Redirect::back()->withErrors($user->errors());
}

如果您不需要检查验证,可以使用

$user->forceSave();