Laravel 不将空值更新到列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53631528/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:11:42  来源:igfitidea点击:

Laravel not updating null values to column

laraveleloquentlaravel-5.7

提问by Jishad

Migration

移民

Schema::create('users', function (Blueprint $table) {
        $table->increments('user_id');
        $table->string('username',50)->unique();
        $table->date('start_date');
        $table->date('end_date')->nullable();
        $table->timestamps();
    });

Here start_date set as column type date and nullable

这里 start_date 设置为列类型日期并且可以为空

When running Insert function like below its inserting null values

当运行如下所示的插入函数时,它会插入空值

$insert = [
    'username'  =>strtoupper(request('username')),
    'password'  =>Hash::make(request('password')),
    'start_date'  =>date('Y-m-d',strtotime(request('start_date'))),
  ];
  if(request()->filled('end_date')){
    $insert['end_date'] = date('Y-m-d',strtotime(request('end_date')));
  }
  User::create($insert);

enter image description here

在此处输入图片说明

When Updating the same row left blank as end_date input,

当更新与 end_date 输入相同的行留空时,

$user = User::GetWithEncrypted(request('user_id'));
$update ['start_date'] = date('Y-m-d',strtotime(request('start_date')));
if(request()->filled('end_date')){
  $update['end_date'] = date('Y-m-d',strtotime(request('end_date')));
}else{
  $update['end_date'] = 'NULL';
}
$user->update($update);

In Table, it comes like below enter image description here

在表中,它如下所示 在此处输入图片说明

How can I make it NULL like insert function in update? My strict mode is false now, If I make it true it will throw an exception of invalid data for the end_date column.

我怎样才能让它像更新中的插入函数一样为空?我的严格模式现在是假的,如果我让它为真,它将为 end_date 列抛出无效数据的异常。

回答by Harry

Try replacing

尝试更换

}else{
  $update['end_date'] = 'NULL';
}

with

}else{
  $update['end_date'] = null;
}

'NULL' is a string whereas null is truly null.

'NULL' 是一个字符串,而 null 是真正的 null。

回答by Bhoomi Patel

you have 2 solution for this problem:

对于这个问题,你有 2 个解决方案:

1.

1.

$user = User::GetWithEncrypted(request('user_id'));
    $update ['start_date'] = date('Y-m-d',strtotime(request('start_date')));
    if(request()->filled('end_date')){
      $update['end_date'] = date('Y-m-d',strtotime(request('end_date')));
    }else{
      $update['end_date'] = '".date('00:00:00')."';
    }
    $user->update($update);

2. you have to set default in mysql database on end date field

2.您必须在结束日期字段的mysql数据库中设置默认值

enter image description here

在此处输入图片说明