This is very wired!
I have an AR model, which is not saved into the database after I called the save() method. However the save() and validate() methods returns True.
This is my sync model:
<?php
namespace common\modules\tube\models;
use Yii;
use common\modules\tube\models\queries\SyncQuery;
/**
* This is the model class for table "{{%sync}}".
*
* @property integer $id
* @property string $type
* @property string $data
* @property integer $result
* @property integer $created_at
*/
class Sync extends \yii\db\ActiveRecord {
const RESULT_FAILED = 0;
const RESULT_SUCCESS = 1;
const TYPE_ADDED = 'Added';
const TYPE_DELETED = 'Deleted';
/**
* @inheritdoc
*/
public static function tableName() {
return '{{%sync}}';
}
/**
* @inheritdoc
*/
public function __construct($config = array()) {
$this->data = json_decode($this->data, true);
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function rules() {
return [
[['type', 'result'], 'required'],
[['data'], 'string'],
[['result', 'created_at'], 'integer'],
[['type'], 'string', 'max' => 100],
];
}
/**
* @inheritdoc
*/
public function attributeLabels() {
return [
'id' => 'ID',
'type' => 'Type',
'data' => 'Data',
'result' => 'Result',
'created_at' => 'Created At',
];
}
/**
* Get the data in array format instead of json.
*
* @return array of data
*/
public function getData() {
return json_decode($this->data, true);
}
/**
* @inheritdoc
*/
public function beforeSave($insert) {
if (is_array($this->data)) {
$this->data = json_encode($this->data);
}
$this->created_at = time();
// returns true - parent::beforeSave($insert);
var_dump(parent::beforeSave($insert));
return parent::beforeSave($insert);
}
/**
* @inheritdoc
* @return SyncQuery the active query used by this AR class.
*/
public static function find() {
return new SyncQuery(get_called_class());
}
}
The database connection fine, because I have Video AR model too, which is saved!
Where the sync model is saved.
public function saveSyncModel($type, $result, $data) {
return $this->createSyncModel($type, $result, $data);
}
private function createSyncModel($type, $result, $data) {
$syncModel = new Sync();
$syncModel->attributes = [
'type' => $type,
'data' => json_encode($data),
'result' => $result,
];
// returns true
var_dump($syncModel->validate());
// returns true but the sync table is empty!
var_dump($syncModel->save());
if (!$syncModel->save()) {
throw new Exception('Sync model was not saved!');
}
return $syncModel;
}
When I run this code, then the validate() and save() method will return True! So there is no validation error. The Exception with ‘Sync model was not saved!’ message is not thrown.
But when I query the database then the ‘sync’ table is empty. Is it a bug?