Yii Framework Forum: How to get ID of last inserted record - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

How to get ID of last inserted record Rate Topic: *---- 1 Votes

#1 User is offline   Blue Sapphire 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 35
  • Joined: 27-February 10

Posted 11 May 2010 - 02:39 PM

How can I get ID of last inserted record/row from database table through YII model class object.

Thanks in advance
0

#2 User is offline   PoL 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 506
  • Joined: 05-November 08
  • Location:Buenos Aires, Argentina

Posted 11 May 2010 - 02:49 PM

If your model is called Model, and has a property called id (aka, the PK of the table), then you can acces this way:



//...
$model = new Model();
// do your stuff....
$model->save();

$the_id = $model->id;

//...


Simple, but effective
Don't say what you think, think what you say
The problem is communication! Excess of communication!
1

#3 User is offline   andy_s 

  • Random Member Title
  • Yii
  • Group: Moderators
  • Posts: 1,526
  • Joined: 22-June 09
  • Location:Russia, Kostroma

Posted 11 May 2010 - 02:53 PM

After a model is inserted into db, it's "id" property is automatically updated, so you can easily get it: $model->id (or $this->id from inside the model class).

You can also get the last insert id from the corresponding CDbConnection's property: http://www.yiiframew...InsertID-detail
2

#4 User is offline   Blue Sapphire 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 35
  • Joined: 27-February 10

Posted 12 May 2010 - 03:50 AM

It is not showing last inserted ID of database table.

Following is model:

class WaTabMod extends CActiveRecord {


    public static function model($className = __CLASS__){
            return parent::model($className);
    }


    public function tableName(){
        return 'watable';
    }

    public function attributeLabels(){
        return array(
                'id'         => 'Id',
                'wausername' => 'Wa Username',
                'wapassword' => 'Wa Password',
                'waemail'    => 'Wa Email'
        );
    }

}



Following is 'create' method of Controller class:

 public function actionCreate(){
        $model = new WaTabMod;
 
        if(isset($_POST)){

            echo '<pre>';                
                  print_r($model->id);
            echo '</pre>';

        }
        $this->render('form', array('model' => $model));
    }


And following is schema :

--
-- Table structure for table `watable`
--

CREATE TABLE IF NOT EXISTS `watable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `wausername` varchar(128) NOT NULL,
  `wapassword` varchar(128) NOT NULL,
  `waemail` varchar(128) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ;



Can some one guide me why Iam unable to get value of "id" of last inserted record.

Thanks in advance
0

#5 User is offline   Spyros 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 461
  • Joined: 14-April 09
  • Location:Athens - Greece

Posted 12 May 2010 - 04:02 AM

You have to use $model->save() in order to insert the record in the DB and get the id
0

#6 User is offline   Blue Sapphire 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 35
  • Joined: 27-February 10

Posted 12 May 2010 - 06:03 AM

What should I do, if my 'id' column is not set as AUTOINCREMENT and I have to set its value manually on each new record insertion.

Can I use http://www.yiiframew...InsertID-detail for this purpose. If so,then can some one guide me how to use it.

Thanks in advance
0

#7 User is offline   Maurizio Domba Cerin 

  • Yii - Yesss It Is !!!
  • Yii
  • Group: Yii Dev Team
  • Posts: 4,367
  • Joined: 12-October 09
  • Location:Croatia

Posted 12 May 2010 - 07:47 AM

lastInsertID works only for autoincrement fields... and only if you use it after insert or update...

If you don't have an autoincrement field than you should give the next value to the field...

one way would be in a transaction first to "select max(field)" so to get the max value of that field and give the returned value+1 to the new record, then save the new record

second way would be to have a table counter where you would keep the nex value... so again in a transaction read the counter value... assign to new record, save new record, increment counter value and save to counter table...
Find more about me.... btw. Do you know your WAN IP?
0

#8 User is offline   Blue Sapphire 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 35
  • Joined: 27-February 10

Posted 12 May 2010 - 09:25 AM

Thanks for reply. What I got from your reply is ----- I have to make a general purpose function which will return maxid of the table. I have concept as follows :
public function myMaxID($tableName, $pkColumnName){
   // Sql statement to get max id of a table 
   return maxId;
}


Now Iam seeking guidance that where I should place this code so that it should be available in all models and controllers.

Thanks in advance
0

#9 User is offline   tri 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,651
  • Joined: 20-November 08
  • Location:Stockholm, Sweden

Posted 12 May 2010 - 09:55 AM

View PostBlue Sapphire, on 12 May 2010 - 09:25 AM, said:

Thanks for reply. What I got from your reply is ----- I have to make a general purpose function which will return maxid of the table. I have concept as follows :
public function myMaxID($tableName, $pkColumnName){
   // Sql statement to get max id of a table 
   return maxId;
}


Now Iam seeking guidance that where I should place this code so that it should be available in all models and controllers.

Thanks in advance


I think you should create a base class and declare your models to inherit from it
class ActiveRecord extends CActiveRecord 
{
  public static function model($className=__CLASS__)
  {
    return parent::model($className);
  }
  ...
}


You can make your suggested function a public member of the base class, but since tableName and tableSchema->primaryKey are available as members I would consider to extend or overload save().

(not tested)
/Tommy
Don't forget to read The Definitive Guide to Yii (en) (sv) | The class reference has the details
0

#10 User is offline   rackycz 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 53
  • Joined: 16-December 09

Posted 13 October 2011 - 04:07 AM

Hi.
Very important thing is (nobody and no manual mentioned it) to unset the ID attribute from $model->attributes like this:

 
$record = new MyModel;
$record->attributes = $_POST["dataFromForm"];
$record->unsetAttributes(array('my_id_column'));
$record->save();
$myNewId = $record->my_id_column;


This must be done if 'my_id_column' was in the form that was just confirmed and that you want to save now. If you do not unset this attribute, Yii has empty string in it, considers it to be a known value and does not refresh it after saving. The value must be NULL when saving.
2

#11 User is offline   Sazzad Tushar Khan 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 15-January 13

Posted 05 March 2013 - 02:21 PM

Neither $model->id
Nor $model->primaryKey
Nor Yii::app()->db->getLastInsertId();
is working
Although data is saving
:(
0

#12 User is offline   vincenzo 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 09-July 13

Posted 09 July 2013 - 04:17 AM

View PostSazzad Tushar Khan, on 05 March 2013 - 02:21 PM, said:

Neither $model->id
Nor $model->primaryKey
Nor Yii::app()->db->getLastInsertId();
is working
Although data is saving
:(

I have the same problem on one model/table. On most models it works but not on every.
It seems to be some bug in ActiveRecord implementation, because when i did var_dump there wasn't ID field on dumped data.

my workaround is:
        public function afterSave()
        {
            parent::afterSave();
            $this->ID_FIELD = Yii::app()->db->getLastInsertID(SEQUENCE_NAME);
        }


I use sequence name because i work with postgresql, maybe on mysql it's not necessary
0

#13 User is offline   joepages 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 4
  • Joined: 12-November 13

Posted 19 November 2013 - 04:12 PM

Hey guys!

I'm having a problem very similar to yours.. What I want to do is to get de Max ID of a table so I can create a folder named as the last ID I just got..

Any ideas?
0

#14 User is offline   SITDnow 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 11-April 14
  • Location:Berlin - Germany

Posted 11 April 2014 - 05:16 AM

Hi Guys,

Today I run in the same issue. My fault was that my primary key was an empty string.
But the primary key will only overwritten when its NULL (===). See CActiveRecord::insert (line 1082).

So when you insert a new Model, add before validate() and save() just:
if(empty($model->id)){ $model->id = NULL; } //id is my primary key

after save/insert you get the key with $model->id. This might happen when you populate the model from a form.

Hope i could help some googlers :)
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users