Yii uuid model save returning null for primary key

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.

Answers


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.


Need Your Help

C#: detecting if running as super user, both in Windows and Mono

c# .net mono

this question is actually a duplicate of this one. I want to detect if my program is being run either with privilege elevation in Winows through UAC, or as root in Unix/Mono.

AngularJS directive that uses the original element type in template

javascript angularjs angularjs-directive

I'm developing UI and typography based directives for Angular. In such cases, the element the directive is being applied on is unknown - anything from a div, span, h1 to an h5.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.