Laravel 5 播种机 - 数据库中的多行
Laravel 5 Seeder - multiple rows in DB
我想知道是否可以像这样(或类似的东西)插入多行:
<?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'
]
);
}
}
我的数据库中有一个 table 设置,其中包含列 键和值 。
上面代码的问题是他只插入了第一个......
您可以使用 eloquent 中的插入方法进行批量保存,例如
Settings::insert([[
'key' => 'username',
'value' => 'testusername'
],
[
'key' => 'password',
'value' => 'plain'
]]);
您需要将数组包装在另一个数组中,因此它看起来像这样:
DB::table('settings')->insert([
[
'key' => 'username',
'value' => 'testusername'
],
[
'key' => 'password',
'value' => 'plain'
]
]);
注意环绕数组。
您现在所做的实际上是将两个单独的数组发送到 insert()
方法。
只需在 运行 方法中重复 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'
]
);
我想知道是否可以像这样(或类似的东西)插入多行:
<?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'
]
);
}
}
我的数据库中有一个 table 设置,其中包含列 键和值 。
上面代码的问题是他只插入了第一个......
您可以使用 eloquent 中的插入方法进行批量保存,例如
Settings::insert([[
'key' => 'username',
'value' => 'testusername'
],
[
'key' => 'password',
'value' => 'plain'
]]);
您需要将数组包装在另一个数组中,因此它看起来像这样:
DB::table('settings')->insert([
[
'key' => 'username',
'value' => 'testusername'
],
[
'key' => 'password',
'value' => 'plain'
]
]);
注意环绕数组。
您现在所做的实际上是将两个单独的数组发送到 insert()
方法。
只需在 运行 方法中重复 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'
]
);