G
G
Glory2021-06-10 20:35:24
PHP
Glory, 2021-06-10 20:35:24

How to get the max id and add the element with id+1 before it's taken?

I use two similar models and they should not have the same value in the id field. That is, the uniqueness within the two models must be respected. I solved this problem using the function:

static function getNextId() {
        $mpMaxId = MasterProduct::max('id');
        $gpMaxId = GroupedProduct::max('id');
        if ( $mpMaxId > $gpMaxId ) {
            return $mpMaxId+1;
        } else {
            return $gpMaxId+1;
        }
    }

And in most cases it works. The function always returns the maximum of the two tables ID+1 and this identifier is filled in before writing a new model. BUT here it happens that when you try to save, there is a curse on the non-uniqueness of the key. What can be wrong?

Can somehow book this id in a transaction? Or maybe several users created elements (products) at the same time, and while we were getting the id for one, the other has already captured this id?

How can we be? to throw this id into redis and get it from there?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question