How to correctly save the date in Oracle database using yii2?

In the Oraklovsky table a field date in a date.

Model

public function behaviors() { return [ [ 'class' => AttributeBehavior::className(), 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['DATE'], ActiveRecord::EVENT_BEFORE_UPDATE => ['DATE'], ], 'value' => new Expression("TO_DATE('" //$this->DATE .Yii::$app->session->get('DATE') ."','YYYY-MM-DD HH24:MI:SS')"), ], ]; } 

The controller in the creation and editing actions use the entry to the session as it does not come out to get through $ this-> DATE in the model.

 Yii::$app->session->set('DATE', $date ); 

The question is how to correctly save the date entered by the user without using the session crutch.

    1 answer 1

    First, you can set the date format used for the connection.
    Secondly, you can modify beforeSave and afterSave for automatic conversion.
    Thirdly, it is described quite fully here: https://github.com/yiisoft/yii2/issues/6004

    I quote an example of the code on the link:

     use yii\db\Expression; class ActiveRecord extends \yii\db\ActiveRecord{ private $dateFormat = 'YYYY-MM-DD hh24:mi:ss'; public function dates() { return ['DT_EVENT']; } public function beforeSave($insert) { if(parent::beforeSave($insert)){ foreach($this->dates() as $attribute){ $this->$attribute = new Expression("to_date('" . $this->$attribute . "','{$this->dateFormat}')"); } return true; }else{ return false; } } public function afterSave($insert, $changedAttributes) { // restore dates foreach($this->dates() as $attribute){ $this->$attribute = str_replace(array("to_date('", "','{$this->dateFormat}')"), '', $this->$attribute->expression); } } }