I'm able to save data to the database and it creates a uuid in the primary key column(id). When I call $model->save(); and access $model->id afterwards, it returns:
{"expression":"UUID()","params":[]}
It should return the actual value in the database...How can I get the actual value that mysql stores?
I have a beforeSave function that adds in the uuid:
public function beforeSave() {
if ($this->isNewRecord)
$this->id = new CDbExpression('UUID()');
return parent::beforeSave();
}
I have also tried creating a trigger that executes the mysql uuid function before update on the id...The $model->id then returns null.
The problem is that you are telling Yii to run a MySQL function to insert into the DB. And it does so just fine, but Yii does not re-read the record afterwards to get the value. To re-read it would be inefficient because what you are doing is not very used and a read from the DB is not necessary usualy. You can go around this in 2 ways:
1) to read the value yourself from the db. You can do a $model->save(); $model->refresh(); right after and you should have the fresh data in the $model
2) you can make your function do a
public function beforeSave() {
if ($this->isNewRecord)
$this->id = Yii::app()->db->createCommand('select UUID()')->queryScalar();
return parent::beforeSave();
}
I have not tested this but you get the idea.
This will go to the DB, run UUID() and return to yii the result. By assigning to $this->id a string instead of a mysql command you will be able to use right away the value without doing a refresh. This will still use MySQL to get the UUID, so it will still put some stress on the server.
Usually I do something like
public function beforeSave() {
if ($this->isNewRecord)
$this->hash = hash('ripemd160',microtime());
return parent::beforeSave();
}
So I do not use the MySQL server at all, but because you use your column as the ID you might want UUID() to generate a truly unique ID.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.