Laravel 5 Seeder - multiple rows in DB

倖福魔咒の 提交于 2020-01-01 10:14:09

问题


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 settings in my database with columns key & value.

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


回答1:


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.




回答2:


you can use insert method from eloquent for bulk save like

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



回答3:


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

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

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

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


来源:https://stackoverflow.com/questions/32589426/laravel-5-seeder-multiple-rows-in-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!