3

I wish to get the auto increment id from my db and call inside my controller.

The 'id' in db is primary key with auto increment.

I tried:

$id = $model->id;
$id = $model->find('id');
$id = $model->findByPK('id');

But the value is blank, any suggestion for me to get the correct id?

Reason why I need the id value is because I need id mix with other value and save into other column.

Thanks.

TheSmile
  • 358
  • 3
  • 9
  • 34

6 Answers6

4
$newId = YourModel::find()->max('id') + 1;
lubosdz
  • 4,210
  • 2
  • 29
  • 43
  • This won't work on tables with a high rate of inserts. It may respond after other rows have been inserted and give you the wrong id. – Harry B Nov 15 '19 at 10:08
2

AUTO_INCREMENT is a special value which may differ from the ID of the last record.

  • If records deleted, the AUTO_INCREMENT will still continue.
  • If records failed to insert, the AUTO_INCREMENT will still continue.

Assume you are using MySQL, you can see its value in phpMyAdmin.

  1. Open a database, then a table.
  2. Switch to the Operations tab.
    table-operations
  3. Find the AUTO_INCREMENT field under Table options. auto-increment-field

So you should obtain its value, especially when you depend on the AUTO_INCREMENT of your database.

For inserting one record, getting the LAST_INSERT_ID() could be an option. But I still don't prefer to do triple operations (insert, read ID, update). Better to minimize the I/O operations (read AUTO_INCREMENT, insert).

In my case, I need to import data from an Excel document. Surely, when performance is important, I cannot depend on the ActiveRecord model. So I use batchInsert() command.

I am adopting this answer for getting the AUTO_INCREMENT value in MySQL.

$lastModelId = Yii::$app->db->createCommand("
    SELECT `AUTO_INCREMENT`
    FROM  INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = DATABASE()
    AND   TABLE_NAME   = 'my_table'
")->queryScalar();

If using table prefix:

$lastModelId = Yii::$app->db->createCommand("
    SELECT `AUTO_INCREMENT`
    FROM  INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = DATABASE()
    AND   TABLE_NAME   = :TableName
")->bindValues([
    ':TableName' => MyModel::getTableSchema()->name,
])->queryScalar();
Yahya
  • 198
  • 1
  • 5
  • 13
  • 1
    This is the fastest and most straigtforward way to retrieve autoincrement ID. Just a small correction - variable `$lastModelId` actually holds `next model id`. – lubosdz Oct 02 '17 at 10:31
0

The easiest way would be to get the new ID after saving the record. After that you can do what you need and save it again. Sth like this:

<?
$model = new YourModel;
$model->field1 = 'some value';
$model->field2 = 'some value 2';
//...
$model->save();

// now you have the new ID and you can use it
$id = $model->id;

// do what you need e.g.
$model->field3 = $field2 + $id;
$model->save();
?>
Asped
  • 3,083
  • 4
  • 31
  • 52
0

this worked for me.

public static function getAutoIncrement($table_name)
{
    $q = new Query();
    $res = $q->select("AUTO_INCREMENT")
        ->from('INFORMATION_SCHEMA.TABLES')
        ->where("TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '" . $table_name . "'")
        ->one();
    if($res)
        return $res["AUTO_INCREMENT"];
    return false;

    //or use this

    //$q = "SELECT `AUTO_INCREMENT` FROM  INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '" . $table_name . "'";
    //$auto_increment = Yii::$app->db->createCommand($q)->queryScalar();
    //return $auto_increment;
}
yousef
  • 1,240
  • 12
  • 13
-1

I found my own aswer:

$max = Yii::app()->db->createCommand()->select('max(id) as max')->from('TABLENAME')->queryScalar();

$id = ($max + 1);

print_r($id);

Thanks.

TheSmile
  • 358
  • 3
  • 9
  • 34
  • 3
    the problem with this can be, that if you do not lock the table before, some other proces in your application can possibly write a new record in the meantime, and then the ID you got may not be correct – Asped Oct 23 '14 at 08:34
  • 3
    Do not use this... you will have problems if you have say 1000 users that make the same request at the EXACT same time. Please check my answer – Ares Draguna Oct 23 '14 at 08:38
-1

You are going about this the wrong way...

$model->id This is available if you have instantiated the $model prior so:

$model = new Model();
$id = $model->id; //this will work if id is the exact name of the column in db

$model->find('id') This finds elements in DB based on the id... but the syntax in wrong so it would throw an error

$model->findByPK('id') Again... find by pk returns a single row from DB if a match with the primary key (which you should have before making this call)

In conclusion, I would recommend the first way but do not forget to instantiate the model first. Otherwise, you can do something like...

$model = Model::model()->findByAttributes(array('some_attribute' => $attribute_value));
$id = $model->id;

Hope this helps!
Keep on coding!
Ares.

Ares Draguna
  • 1,641
  • 2
  • 16
  • 32
  • with your solution you would not get the auto increment value, you would not even get the ID for a new value. this can be used only if you already have a record saved. Instanciating a model does nothing but empty values. Only the last solution of yours would do something, all others are nonsense – Asped Oct 23 '14 at 08:48
  • @Asped, bro... I posted my answer explaining what he did wrong! Read his question and then judge my answer! He tried $model->id, $model->find('id'), and $model->findByPK('id') and I explained to him each individual method what it does and what he gets. And you are saying that the first one, where you instantiate model and then call it with $model->id is not working??? Then YOU have no ideea about Yii my friend, and you got the above answer by a google search ;) – Ares Draguna Oct 23 '14 at 08:52
  • if you make `new Model()`, then you get a new clean model. with no values in it -> so you surely do not get the latest ID in it. you get NULL or some other default value you have set in your DB. `$model->findByPK('id')` would search for a record where the primary key matches the value 'id', regardles of the name of the PK field. – Asped Oct 23 '14 at 09:04
  • findByPK you just gaved the same explanation that I did and new Model() does not create a new "clean" model it instantiates a model of a certain DB object ;) You can manipulate any value you want ;) and of course you do not have access to the last inserted ID, but you CAN manipulate it and every other value there. In fact, it is the save example that you gived and got accepted so help me out here... I don't get it... When you say it is cool when I say it is bulls@#t? – Ares Draguna Oct 23 '14 at 09:09
  • sorry I do not want to argue :) but the question asked was to get the auto increment ID, he did not have a problem with the data manipulation, nor with accessing the values. And yes, `new Model` as you say instantiates a model of a certain DB object - but the point is - it is empty=clean call it however you want, it does not get any data from the DB yet, so you cannot get any values from you DB, so this has nothing to do with the question asked. – Asped Oct 23 '14 at 09:30