How can I set a date to NULL in Yii?

后端 未结 3 814
生来不讨喜
生来不讨喜 2020-12-15 07:22

I have a date column that usually takes values as dd.MM.yyyy. Its validation rule in the model\'s rules() is this:

array(\'start, e         


        
相关标签:
3条回答
  • 2020-12-15 07:26

    Assigning a CDbExpression to the field will (and should) never pass validation; the validator allows null but it definitely cannot allow an arbitrary CDbExpression as the value of the field; this should not be surprising.

    If you wanted to write null to the database then do it simply with $user->start = null -- there is no reason to involve CDbExpression at all here.

    Another approach you could use in case you did need to use CDbExpression would be to tell save not to validate the record and do it manually, as in:

    $attributes = $user->attributeNames();
    if (empty($csv_data)) {
        $user->start = new CDbExpression('NULL');
        $attributes = array_diff($attributes, array('start')); // don't validate this
    } else {
        $user->start = $csv_data;
    }
    
    if ($user->validate($attributes)) { // validate only attributes we want here
        $user->save(false); // no validation at all here
    }
    
    0 讨论(0)
  • 2020-12-15 07:27

    in model rules():

    array('start, end', 'date', 'format' => 'dd.MM.yyyy'),
    array('start, end', 'default', 'setOnEmpty' => true, 'value' => null),
    

    also,

    if (empty($csv_data)) {
      $user->start = null;
    } ...
    

    should do the trick too.

    0 讨论(0)
  • 2020-12-15 07:44

    The trivial fix for this is not to set the value at all during creation:

    if (!empty($csv_data)) {
      $user->start = $csv_data;
    }
    

    This way, the date will not be set and thus appear as empty, which also passes validation.

    0 讨论(0)
提交回复
热议问题