为什么字段不更新?

时间:2018-01-20 17:48:56

标签: laravel laravel-5 laravel-5.3

我有以下查询功能:

    $user = User::findOrFail($id)->first();

    if($user->status == 1) {
        $status = 0;
    } else {
        $status = 1;
    }

    User::where("id", $id)->update(["status" => $status]);

当我看到数据库表时,字段status未更新为1

状态提交说明:

status         | int(11)          | NO   |     | 1  

2 个答案:

答案 0 :(得分:2)

为什么不从实例化的用户对象中保存状态?

你可以这样做:

  $user = User::findOrFail($id)->first();

if($user->status == 1) {
    $status = 0;
} else {
    $status = 1;
}

$user->update(["status" => $status]);

答案 1 :(得分:1)

您可以这样做以切换布尔属性:

$user = User::findOrFail($id);
$user->status = !$user->status;
$user->save();

或者:

$user = User::findOrFail($id);
$user->status = $user->status === 1 ? 0 : 1;
$user->save();