还原软删除的实体会在deleted_at列中设置无效的时间戳

时间:2017-03-10 13:38:24

标签: php mysql laravel laravel-4

我正在尝试在Laravel 4.2中恢复软删除的实体,但它会将deleted_at列的时间戳设置为无效格式。

不是将其设置为NULL,而是将其设置为0000-00-00 00:00:00,并且它阻止我实际恢复软删除的实体,因为Laravel会将其识别为已删除,因为该列不为空。

我尝试使用和不使用deleted_at属性的setter,但它不起作用。

代码实际上非常简单:我提交一个PUT请求以使deleted_at列无效,以便用户恢复,但不成功。

// Javascript
$("#enable-user").on('click', function (event) {
    var action = $(this).attr('action');

    swal({
        title: "Are you sure?",
        text: "Do you want to reactivate this user?",
        type: "warning",
        showCancelButton: true,
        html: true,
        cancelButtonText: "Cancel",
        confirmButtonText: "Continue",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
    },
    function(isConfirm) {
        if (isConfirm) {
            $.ajax({
                type: 'PUT',
                url: action,
                headers: {
                    'X-CSRF-Token': $("input[name='_token']").attr('value')
                },
                data: {
                    deleted_at: null
                },
                success: function(data) {
                    sweetAlert("Sii!", "User re-activated successfully!", "success");
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status === 401) {
                        sweetAlert("Oops...", jqXHR.responseJSON.message, "error");
                    } else {
                        sweetAlert("Oops...", "Something went wrong!", "error");
                    }
                }
            });
        }
    });
});
// UsersController
public function updateUser($userId)
{
    $input = Input::all();
    $user  = User::withTrashed()->where('id', '=', $userId)->firstOrFail();

    if (array_key_exists('exports', $input)) {
        $user->exportAccounts()->sync([]);
        $user->exportAccounts()->sync($input['exports']);
        unset($input['exports']);
    }

    if (array_key_exists('regions', $input)) {
        $user->regions()->sync([]);
        $user->regions()->sync($input['regions']);
        unset($input['regions']);
    }

    $user->update($input);

    $user->queueUpdateToAlgolia();

    return Response::json([], 200);
}

这是恢复后数据库中显示的内容:

database

1 个答案:

答案 0 :(得分:0)

由于#laravel IRC中的helloNL已经解决了问题。

显然,在Laravel中,JavaScript不会识别为NULL,而是将其作为空字符串识别。

所以我必须从这里编辑我的模型设定器:

public function setDeletedAtAttribute($value)
{
    if ($value === NULL) {
        $this->attributes['deleted_at'] = null;
    } else {
        $this->attributes['deleted_at'] = $value;
    }
}

对此:

public function setDeletedAtAttribute($value)
{
    if ($value === NULL  || $value === "") {
        $this->attributes['deleted_at'] = null;
    } else {
        $this->attributes['deleted_at'] = $value;
    }
}