【问题标题】:Setting Default Value for Primary Key in Laravel Migration for sqlite在 Laravel Migration for sqlite 中设置主键的默认值
【发布时间】:2015-01-25 09:11:07
【问题描述】:

我在下面创建了数据库迁移。我想做的是创建一个以 id 作为主键的帐户表。但是,我不希望密钥从 1 开始自动递增。相反,我希望它从 800500 开始自动递增。

有没有办法像这样设置主键的默认值?

我目前正在使用 Laravel v4.2.11 和 sqlite v3.8.3。

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAccountsTable extends Migration {

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('accounts', function(Blueprint $table)
    {
        $table->increments('id')->unsigned()->default(800500);
        $table->string('name', 100);
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::drop('accounts');
}

}

【问题讨论】:

    标签: laravel-4 sqlite


    【解决方案1】:

    schema builder 中的default 方法

    声明列的默认值

    如果您需要增量从给定值开始,请查看this 答案。 您将查询添加到迁移中:

    public function up()
    {       
        Schema::create('accounts', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('name', 100);
            $table->timestamps();
        });
        DB::statement("UPDATE SQLITE_SEQUENCE SET seq = 800500 WHERE name = 'accounts'");
    }
    

    没有“laravel”方法可以做到这一点。

    【讨论】:

    • 感谢@edpaez 的快速回复。不幸的是,这并没有做到。当我按照您的规定运行迁移后运行种子文件时,它仍然为我的第一条记录返回 ID 1。我应该更清楚地知道默认值是列的默认值,而不是初始值。哦。
    猜你喜欢
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2015-07-31
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    相关资源
    最近更新 更多