【发布时间】:2014-08-22 11:08:49
【问题描述】:
我有一个 Laravel 项目,我想将超过 900 个城市作为数据库种子插入数据库。
例如我可以这样做:
$state_id = State::whereName('state name')->pluck('id');
$city = new City();
$city->name = 'my city name';
$city->state_id = $state_id;
$city->save();
在我的城市模型中,我定义了另存为:
public function save(array $options = array()) {
$this->url = $this->createUrl($this->name);
parent::save($options);
}
所以它也为城市创建了 url。
我可以放 900 次这样的代码块,但有一个问题 - 它将在单独的查询中运行,因此将这些数据插入数据库需要 30 秒以上。
例如,我可以这样做:
DB::table('cities')->insert(
[
[
'name' => 'City name',
'url' => Slug::create('City name'),
'created_at' => $now,
'updated_at' => $now,
'state_id' => $state_id
],
[
'name' => 'City name 2',
'url' => Slug::create('City name 2'),
'created_at' => $now,
'updated_at' => $now,
'state_id' => $state_id
],
]);
这样我可以在一个 SQL 查询中插入许多记录,但我认为这不是很好的解决方案 - 我需要手动设置所有数据库字段,但只需 3-4 秒即可将所有数据插入数据库。
问题是 - 是否可以创建模型并使用一些魔术方法返回准备好的 PHP 数组以在多桩插入中使用它(我读到 Eloquent 不能用于在一个查询中插入多条记录)?
我认为这样的代码会更好:
$state_id = State::whereName('state name')->pluck('id');
$city = new City();
$city->name = 'my city name';
$city->state_id = $state_id;
$city1 = $city->saveFake(); // magic method that returns complete array
$city = new City();
$city->name = 'my city name';
$city->state_id = $state_id;
$city2 = $city->saveFake(); // magic method that returns complete array
DB::table('cities')->insert(
[
$city1,
$city2,
]);
【问题讨论】:
标签: php laravel laravel-4 seeding