updateExistingPivot()无效

时间:2015-02-09 10:27:40

标签: laravel laravel-4 eloquent

我试图像这样更新数据透视表:

public function updatePermission($id, $permissionId)
{
    $permissionValue = Input::get('value');
    $user = User::find($id);

    $perms = ['value' => $permissionValue];
    $user->permissions()->updateExistingPivot($permissionId, $perms);
}

此枢轴先前已使用以下命令创建:

public function attachPermission($id)
{
    $permissionId = Input::get('id');
    $permissionValue = Input::get('value');
    $user = User::find($id);

    if (!$user->permissions->contains($permissionId)) {

        $user->attachPermissionById($permissionId);
        $perms = ['value' => $permissionValue];
        $user->permissions()->updateExistingPivot($permissionId, $perms);

    } else {

        return Response::json(array('error' => 'Permission ' . $permissionId . ' is alreay set for user ' . $user->id));

    }

    return Response::json(array('role' => User::with(['roles.permissions', 'permissions', 'students'])->find($user->id)));
}

当命中updatePermission()方法时,它会正常传递,但它不会使用新值更新数据透视表。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

我不会告诉你为什么它不起作用,但我建议你这样做:

public function attachPermission($id)
{
    $permissionId = Input::get('id');
    $value = Input::get('value');
    $user = User::find($id);

    $sync = $user->permissions()->sync([$permissionId => compact('value')], false);

    return (in_array($permissionId, $sync['updated']))
       ? Response::json(...) // permission updated
       : Response::json(...); // permission added
}

它会为您添加或更新新权限。