Laravel 迁移插入 table

Laravel Migrations insert into table

在我的 up() 函数中的 Laravel 5.3 中,如何将数据插入另一个 table?

我只能在更新列等指南中看到内容

只要 table 已经创建,您就可以像在普通 Laravel 代码中那样做。例如:

public function up()
{
    Schema::create('this_table', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
    });

    \DB::table('that_table')->insert([]);
}

正如其他人所建议的那样,您应该考虑将此类逻辑移至数据库播种器中是否更好。但是,我发现有时当您的 table 具有恒定的初始数据时,将此类逻辑放在迁移文件中会更好。

仅供参考,Here 是一个开源 Laravel 项目。

===========5年后编辑=============

我建议任何想要这样做的人都将数据库播种器视为建议的原始答案。现在 Laravel 有一个 schema:dump 命令可以用来压缩你的迁移。如果您有一个包含许多迁移的项目,这可能很有用。对我来说,我有一个有 408 个迁移的项目,现在使用 schema:dump 并不容易,因为迁移中的数据填充方法将丢失。

You can insert to the table as shown below after the table is created.

    DB::table('tablename')->insert([
        ['columnname1' => 1, 'columnname2' => 'Girl'],
        ['columnname1' => 2, 'columnname2' => 'Boy']
    ]);