【问题标题】:Laravel 5 Seeder - multiple rows in DBLaravel 5 Seeder - 数据库中的多行
【发布时间】:2015-09-15 15:02:53
【问题描述】:

我想知道是否可以像这样(或类似的东西)插入多行:

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

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

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

【问题讨论】:

    标签: php mysql laravel row laravel-5.1


    【解决方案1】:

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

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

    注意包装数组。

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

    【讨论】:

    • 我试过这个但得到“找不到列:1054 '字段列表'中的未知列'0'”
    【解决方案2】:

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

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

    【讨论】:

    • 这将失败,因为您实际上是在发送insert(array(...), array(...))。插入需要一个数组数组。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多