如何获取laravel中特定表的自动生成字段的下一个ID?

问题描述 投票:12回答:9

我正在寻找类似的东西:

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

不是

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

有人知道实现这一目标很热吗?

php laravel laravel-5.2
9个回答
9
投票

为我工作:(PHP:7.0-Laravel 5.5)

use DB;

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

7
投票

您可以使用此聚合方法并将其递增:

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

7
投票

您需要执行MySQL查询以获取自动生成的ID。

show table status like 'users'

在Laravel5中,您可以执行以下操作。

public function getNextUserID() 
{

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

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

2
投票

在Laravel5中,您可以执行以下操作。

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

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

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

2
投票

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


0
投票

在MySQL中,您可以通过此查询获取自动生成的ID。

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

0
投票

尝试一下:

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

0
投票

对于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;
    }
}

模型:

<?php // User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use GetNextSequenceValue;
}

结果:

<?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());
    }
}

0
投票

这是我在laravel中使用的代码段,witch可以正常使用

谢谢,

$id=DB::select("SHOW TABLE STATUS LIKE 'Your table name'");
$next_id=$id[0]->Auto_increment;
echo $next_id; 
© www.soinside.com 2019 - 2024. All rights reserved.