简体   繁体   中英

Group based auto increment

In my employees table entities are employee_id, name, type

there are 3 types of employees. those are : ST, WF, WP

So when a employees info enter into the database table would be like this

employee_id  name     type
WP 1          john      WP
WP 2          doe       WP
ST 1          jhonny    ST
WF 1          tuna      WF
ST 2          tian      ST
WP 3          Rian      WP

Problem here is How to enter employee_id auto increment based on type

there is one solution could be like it will count employee type from table and add count+1 based on type. but the problem when multiple user enter employees database into table multiple user will get same count and employee_id won't be unique.

How do i get optimum solution? Thanks

You could try to create unique index on (employee_id, type) and catch exceptions.

For eloquent:

$employee = new Employee($data);

$saved = false;

while (!$saved) {
    try {
        $count = Employee::where('type', $employee->type)->count();
        $employee->employee_id = $employee->type . ' ' . ($count + 1);
        $employee->save();
        $saved = 1;
    } catch (\Illuminate\Database\QueryException $e) {
    }
}

For non-eloquent:

$type = 'some type';    
$saved = false;

while (!$saved) {
    try {
        $count = DB::table('employees')->where('type', $type)->count();

        DB::table('employees')->insert([
            'employee_id' => $type . ' ' . ($count + 1)
            ...
        ]);

        $saved = 1;
    } catch (\Illuminate\Database\QueryException $e) {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM