Oggi mi sono imbattuto in questo problema. Mettete il caso di avere un modello con attributi settati automaticamente in beforeSave
/**
* This is invoked before the record is saved.
* @return boolean whether the record should be saved.
*/
protected function beforeSave() {
if (parent::beforeSave()) {
if ($this->isNewRecord) {
$this->create_time = date('Y-m-d H:i:s', time());
}
$this->update_time = date('Y-m-d H:i:s', time());
$this->updater_id = Yii::app()->user->id;
return true;
} else return false;
}
Ora, quando nella nostra app andremo a fare un $model->update(array(…), quegli attributi non verranno salvati se non li specificheremo nell’array. E’ molto scomodo doverli includere sempre, d’altro canto mi sembra peggio ancora scrivere una cosa del genere
/**
* This is invoked before the record is saved.
* @return boolean whether the record should be saved.
*/
protected function beforeSave() {
if (parent::beforeSave()) {
$this->update_time = date('Y-m-d H:i:s', time());
$this->updater_id = Yii::app()->user->id;
if ($this->isNewRecord) {
$this->create_time = date('Y-m-d H:i:s', time());
} else $this->update(array('update_time', 'updater_id'));
return true;
} else return false;
}
L’esempio qui sopra non funziona perché manda in loop Yii.
Se Yii avesse un attributo contenente le opzioni che si stanno salvando dovrei semplicemente aggiungerle, una cosa del genere intendo
/**
* This is invoked before the record is saved.
* @return boolean whether the record should be saved.
*/
protected function beforeSave() {
if (parent::beforeSave()) {
if ($this->isNewRecord) {
$this->create_time = date('Y-m-d H:i:s', time());
}
$this->update_time = date('Y-m-d H:i:s', time());
$this->updater_id = Yii::app()->user->id;
array_push($this->updateAttributes, array('update_time', 'updater_id'));
return true;
} else return false;
}
Insomma, il problema è inserire in corso di update altri attributes oltre a quelli chiamati esplicitamente.
Che ne dite? Voi come risolvereste?