Reputation: 15
I'm a fairly new yii user, and I have a little project I'm doing. I'm not using Yii's model generator since my queries are pretty custom and I'm still not quite at home with the whole yii active record thing, so I'm sticking to the query builder for now. I've grasped the basic ideas of making sql statements, but I think I'm going to run into a problem with one I need to do.
Basically, I'm inserting data into one table, and I need to get the value of the id column of the just inserted data. The easiest way would be to just do an insert and get the max value of the id column, but I'm pretty sure that's not the correct way to do it - since someone else can insert stuff "at the same time" and I might end up getting the wrong value - and I need the right one because I will be inserting it into another table.
I've seen that the return value of the insert() function is an integer, the number of inserted rows so I can't use that.
Basically, is there a way to get the data I just inserted to a table that's 100% correct & safe - even if someone else inserted something to the table "at the same time"?
Upvotes: 1
Views: 4088
Reputation: 5913
if you have saved the model, you can access it with
$model->id
assuming that id is the auto increment id field in your database. obviously, before the model is saved you can't get it's id
Upvotes: 3
Reputation: 2583
You want getLastInsertId() of the CDbConnection class:
$id = Yii::app()->db->getLastInsertId();
Upvotes: 4