Wednesday, January 12, 2022

[FIXED] Yii - get auto increment id

Issue

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.


Solution

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();
?>


Answered By - Asped

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.