updateExistingPivot()无法正常工作 [英] updateExistingPivot() not working

查看:84
本文介绍了updateExistingPivot()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试像这样更新数据透视表:

I'm trying to update a pivot table like this:

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

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

此枢轴以前是使用以下方式创建的:

This pivot has been previously created with:

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()方法时,它可以通过,但不会用新值更新数据透视表.我在这里做什么错了?

When the updatePermission() method is hit, it passes fine, but it doesn't update the pivot table with the new value. What am I doing wrong here?

推荐答案

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

I won't tell you why it doesn't work, but I suggest you do this:

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
}

它将为您添加或更新新权限.

It will add or update new permission for you.

这篇关于updateExistingPivot()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆