A
A
Andrew Chil2017-06-07 22:06:19
Yii
Andrew Chil, 2017-06-07 22:06:19

How to pull out the id of the last record or find out with what id the user will be created, Yii2?

Good afternoon! Please tell me how to pull the last record from the database in Yii2?
There are users in which id is generated, and when creating a user, I need to already know what id he will have, since he does not upload files differently.
Here you need to pull out the last id and add a unit.
Perhaps someone will suggest a simpler solution.
I would be very grateful for your help!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Andrey, 2017-06-07
@reaferon

$id = Yii::$app->db->getLastInsertID();
Returns the ID of the last inserted record

E
entermix, 2017-06-07
@entermix

Something like this: But you solve the problem incorrectly.

Here you need to pull out the last id and add a unit.
Perhaps someone will suggest a simpler solution.

What if another 100,500 users register at that time?
Add a user, get his ID and only after that link any files or upload them to temporary storage.

D
Dmitry, 2017-06-07
@slo_nik

Good evening.
We created a user and got an id (the easiest option):

if($model->save()){
   return $model->id;
}

M
Maxim Fedorov, 2017-06-08
@qonand

If you need to get the record identifier before saving it to the database, then you should refuse the auto-increment of the identifier (as far as I understand it is used by you now) and do the calculation of the identifier on the application side, or first save the user and then receive it identifier.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question