一次播种多行幼虫5 [英] Seed multiple rows at once laravel 5
问题描述
我目前正在尝试播种我的users表.如果我这样尝试2行,它将失败.如果我只使用单个数组而不是$ users数组中的2个数组来创建一些虚假数据,效果很好.
I'm currently trying to seed my users table. If I try it like this with 2 rows, it fails. It works fine if I just use a single array instead of the 2 arrays inside the $users array to create some fake data.
我在做什么错,正确的方法是什么?
What am I doing wrong, what is the proper way to do this?
class UserTableSeeder extends Seeder {
public function run()
{
DB::table('users')->delete();
$users = [
['id' => 1, 'name' => 'Stephan de Vries', 'username' => 'stephan', 'email' => 'stephan-v@gmail.com', 'password' => bcrypt('carrotz124')],
['id' => 2, 'name' => 'John doe', 'username' => 'johnny', 'email' => 'johndoe@gmail.com', 'password' => bcrypt('carrotz1243')],
];
User::create($users);
}
}
推荐答案
如果必须使用模型,则需要循环:
If you have to use the model you need a loop:
foreach($users as $user){
User::create($user);
}
否则,您可以只使用DB::table()
和insert
:
Otherwise you can just use DB::table()
and insert
:
DB::table('users')->insert($users);
实际上,您也可以在模型上调用insert()
(查询结果相同)
Actually you can also call insert()
on the model (the resulting query is the same)
User::insert($users);
注意,如果您选择insert
方法,则会失去特殊的口才功能,例如时间戳和模型事件.
Note if you choose the insert
method you loose special Eloquent functionality such as timestamps and model events.
这篇关于一次播种多行幼虫5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!