Laravel 5 Seeder - DB 中的多行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32589426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:21:14  来源:igfitidea点击:

Laravel 5 Seeder - multiple rows in DB

phpmysqllaravelrowlaravel-5.1

提问by nielsv

I was wondering if it's possible to insert multiple rows like this (or something like this):

我想知道是否可以像这样(或像这样)插入多行:

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

I have a table settingsin my database with columns key & value.

我的数据库中有一个表设置,其中包含key & value列。

The problem with the code above is that he only inserts the first one ... .

上面代码的问题是他只插入了第一个 ... 。

回答by Chris Magnussen

You need to wrap your arrays in another array, so it would look like this:

您需要将数组包装在另一个数组中,因此它看起来像这样:

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

Notice the wrapping array.

注意包装数组。

What you are doing now is actually sending two separate arrays to the insert()method.

您现在所做的实际上是向该insert()方法发送两个单独的数组。

回答by Imtiaz Pabel

you can use insert method from eloquent for bulk save like

您可以使用 eloquent 中的插入方法进行批量保存,例如

Settings::insert([[
            'key' => 'username',
            'value' => 'testusername'
        ],
        [
            'key' => 'password',
            'value' => 'plain'
        ]]);

回答by Abra?o Pessoa

Just repeate the DB::table code as much as you want inside the run method!:

只需在 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'
            ]
        );