How to get next id of autogenerated field in laravel for specific table?

非 Y 不嫁゛ 提交于 2019-12-20 19:39:10

问题


I am looking for something like :

DB::table('users')->getNextGeneratedId();

not

$user->save($data)
$getNextGeneratedId = $user->id;

Does anybody know hot to achieve this ?


回答1:


This work for me: (PHP: 7.0 - Laravel 5.5)

use DB;

$statement = DB::select("SHOW TABLE STATUS LIKE 'users'");
$nextId = $statement[0]->Auto_increment;



回答2:


You can use this aggregate method and increment it:

$nextId = DB::table('users')->max('id') + 1;



回答3:


You need to execute MySQL query to get auto generated ID.

show table status like 'users'

In Laravel5, you can do as following.

public function getNextUserID() 
{

 $statement = DB::select("show table status like 'users'");

 return response()->json(['user_id' => $statement[0]->Auto_increment]);
}



回答4:


In Laravel5, you can do as following.

$data = DB::select("SHOW TABLE STATUS LIKE 'users'");

$data = array_map(function ($value) {
    return (array)$value;
}, $data);

$userId = $data[0]['Auto_increment'];



回答5:


Try this:

$id = DB::table('INFORMATION_SCHEMA.TABLES')
    ->select('AUTO_INCREMENT as id')
    ->where('TABLE_SCHEMA','your database name')
    ->where('TABLE_NAME','your table')
    ->get();



回答6:


$next_user_id = User::max('id') + 1;




回答7:


In MySQL you can get auto generated id by this query.

SELECT AUTO_INCREMENT
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = "databaseName"
AND TABLE_NAME = "tableName"



回答8:


For PostgreSQL:

<?php // GetNextSequenceValue.php

namespace App\Models;

use Illuminate\Support\Facades\DB;

trait GetNextSequenceValue
{
    public static function getNextSequenceValue()
    {
        $self = new static();

        if (!$self->getIncrementing()) {
            throw new \Exception(sprintf('Model (%s) is not auto-incremented', static::class));
        }

        $sequenceName = "{$self->getTable()}_id_seq";

        return DB::selectOne("SELECT nextval('{$sequenceName}') AS val")->val;
    }
}

The model:

<?php // User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use GetNextSequenceValue;
}

The result:

<?php // tests/Unit/Models/UserTest.php

namespace Tests\Unit\Models;

use App\Models\User;
use Tests\TestCase;

class UserTest extends TestCase
{
    public function test()
    {
        $this->assertSame(1, User::getNextSequenceValue());
        $this->assertSame(2, User::getNextSequenceValue());
    }
}



回答9:


This is the code snippet i used in laravel,witch will work perfectly

thanks,

$id=DB::select("SHOW TABLE STATUS LIKE 'Your table name'");
$next_id=$id[0]->Auto_increment;
echo $next_id; 


来源:https://stackoverflow.com/questions/37210747/how-to-get-next-id-of-autogenerated-field-in-laravel-for-specific-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!