Laravel 5 填充器 - 在数据库中插入多行数据

7
我在想是否可以像这样插入多行(或类似的方式):
<?php

use Illuminate\Database\Seeder;

class SettingTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('settings')->insert(
            [
                'key' => 'username',
                'value' => 'testusername'
            ],
            [
                'key' => 'password',
                'value' => 'plain'
            ]
        );
    }
}

我在数据库中有一个表设置,其中包含列键和值

上面的代码问题在于它只插入第一个...

3个回答

35

你需要将数组包装在另一个数组中,这样它会像这样:

DB::table('settings')->insert([
    [
        'key' => 'username',
        'value' => 'testusername'
    ],
    [
        'key' => 'password',
        'value' => 'plain'
    ]
]);

注意原数组的嵌套。

你现在正在向insert()方法发送两个分离的数组。


我尝试了这个,但是出现了“列未找到:1054在'字段列表'中未知的列'0'”的错误。 - Samay

1
您可以使用Eloquent的insert方法进行批量保存,例如:
Settings::insert([[
            'key' => 'username',
            'value' => 'testusername'
        ],
        [
            'key' => 'password',
            'value' => 'plain'
        ]]);

这会失败,因为你实际上发送的是 insert(array(...), array(...))。插入函数期望一个数组的数组。 - Chris Magnussen

-1

只需在run方法中尽可能多地重复使用DB :: table代码!:

DB::table('settings')->insert(
            [
                'key' => 'username',
                'value' => 'testusername1'
            ]
        );

 DB::table('settings')->insert(
            [
                'key' => 'username',
                'value' => 'testusername2'
            ]
        );

 DB::table('settings')->insert(
            [
                'key' => 'username',
                'value' => 'testusername3'
            ]
        );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接