$object->fill(post()) 不能在 OctoberCMS 中使用空白日期输入

$object->fill(post()) not working with blank date inputs in OctoberCMS

我有一个包含一些日期类型输入的表单:

<input name="some_date" type="date" />

这些字段不是必需的,可以保持不变,因此 some_date 字段在数据库中设置为 "nullable"。这是 plugins/acme/plugin/updates/ 中迁移文件中的行:

$table->date('some_date')->nullable();

问题是,当我尝试使用 Eloquent 的 fill() 方法和 OctoberCMS 的 post() 帮助程序保存表单数据时,我得到 SQL 告诉我我有一个 "Incorrect date value:''".

$object = new SomeObject();
$object->fill(post());
$object->save();

当然,我知道空字符串是无效格式,但不应该这样做吗? post() 不应该处理这个吗?还是我需要传递额外的 setting/var?

否则我只需要遍历 post() 并自己处理空字符串。有点乱。

转念一想,使用 array_filter() 并不是一个好主意。

如果您的模型具有 is_active = false 等虚假值的属性怎么办?

$data = post();

if(is_array($data) && count($data)){

    $data = array_filter($data);
    $object = new SomeObject();
    $object->fill($data);
    $object->save();

}

// $data  = [
//    'some_date' => ''       // false
//    'is_active' => false   // Will be filtered out
// ];

我能想到的更好的方法;

在你的模型中使用 Nullable Trait :

class MyModel extends Model
{
    use \October\Rain\Database\Traits\Nullable;

    protected $nullable = ['some_date'];
}

现在如果some_date = ''那么它将被取消。

使用beforeValidate()beforeSave()模型事件,检查some_date是否为空字符串,手动设置为NULL

public function beforeValidate()
{

    if(empty($this->some_date)){

        $this->some_date = null;

    }

}

在您的模型中定义一个 Mutator 方法并操纵属性的值:

protected $dates = ['some_date'];

public function setSomeDateAttribute($value)
{

    if(empty($value)){
        $this->attributes['some_date'] = null;
    }  else  {
        $this->attributes['some_date'] = $value;
    }

}