【发布时间】:2016-01-30 21:38:45
【问题描述】:
我正在为 Laravel 创建一个自定义包,它需要从数据库中获取一些默认数据(尺寸格式、质量、价格范围)才能工作。
数据应该可以被 Laravel 应用程序编辑(例如:价格变化),所以它需要被包共享。因此,我为包需要使用的表创建了一些迁移,但是提供将填充表的默认数据的最佳方法是什么?
【问题讨论】:
我正在为 Laravel 创建一个自定义包,它需要从数据库中获取一些默认数据(尺寸格式、质量、价格范围)才能工作。
数据应该可以被 Laravel 应用程序编辑(例如:价格变化),所以它需要被包共享。因此,我为包需要使用的表创建了一些迁移,但是提供将填充表的默认数据的最佳方法是什么?
【问题讨论】:
Laravel 提供播种 http://laravel.com/docs/5.1/seeding 以在您使用迁移时使用。
【讨论】:
为迁移中的默认值添加种子代码对我有用,例如:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVocabulariesTable extends Migration
{
public function up()
{
Schema::create('vocabularies', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 100)->nullable();
$table->dateTime('created_at')->nullable();
$table->dateTime('updated_at')->nullable();
$table->softDeletes();
});
$records = [['id' => 1, 'name' => 'category'], ['id' => 2, 'name' => 'tag']];
foreach ($records as $record)
\App\Models\Vocabulary::create($record);
}
public function down()
{
if (Schema::hasTable('vocabularies')){
Schema::drop('vocabularies');
}
}
}
【讨论】: