How to get the last ID saved in the DB to use it inside beforeSave or beforeInsert in a model?


#1

I know that using lastInsertID I get the last inserted ID into the DB table but only after INSERT has completed:

$m->lastInsertID();

so If I use it inside HOOK like afterInsertQuery it works fine:

        $this->addHook('afterInsertQuery', function ($m) {
            $last = $m->lastInsertID();
...

But my question is how can I get the last ID from the DB inside the HOOK beforeInsert or beforeSave?

$this->addHook('beforeSave', function ($m) {

...???

});

The reason is because I need to keep one table with one record all the time, so if I insert another record, the new record must replace the old one, and the ID can be different for this no problem and this unique existing record in this table can be updated or deleted without problems…

any ideas how to get the last ID from DB inside HOOK beforesave or beforeInsert ?

the other thing that I thought maybe Hide the Add New Hotel Button when there record > 1 in that table and show it again when records < 1 in this case I am using CRUD… to add records to the DB

Any ideas how to hide/show this button with this criteria?

thanks


#2

Well.

At first glance on your requirement I think it’s bad DB design to have table at all if it only should have 1 record all the time.

Second - there is no way you can get lastInsertID before you actually insert it. But if you think about getting something like select max(id) from table before you insert new record, then it can be done easily.

Third - if you have to have only last (one) record in your table always, then you can simply delete other records from table before you insert new one. Like this:

$this->addHook('beforeSave', function ($m) {
    $m->action('delete')->execute();
});

#3

You could generate ID in PHP before saving and then set in $model->id. I think ATK Data supports that.


#4

thanks for the tips!