【发布时间】:2016-01-22 03:59:38
【问题描述】:
我正在做我的第一个 laravel 项目。我在我的数据库中创建了两个表并尝试在每个表中播种数据。第一个表(项目)的数据按预期插入,但第二个表中没有插入数据(任务)。当我运行php artisan db:seed command 时,出现以下错误。
"完整性约束违规:1062 重复条目 '1' 用于键 初级
可能是什么原因,我该如何解决?
这是我的扩展迁移课程
public function up()
{
//
Schema::create('projects', function(Blueprint $table)
{
$table->increments('id');
$table->string('name')->default('');
$table->string('slug')->default('');
$table->timestamps();
});
Schema::create('tasks', function(Blueprint $table) {
$table->increments('id');
// $table->integer('project_id')->unsigned()->default(0);
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
$table->string('name')->default('');
$table->string('slug')->default('');
$table->boolean('completed')->default(false);
$table->text('description')->default('');
$table->timestamps();
});
}
项目表的种子类
class projectSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
$projects = array(
['id' => 1, 'name' => 'Project 1', 'slug' => 'project-1', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 2, 'name' => 'Project 2', 'slug' => 'project-2', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 3, 'name' => 'Project 3', 'slug' => 'project-3', 'created_at' => new DateTime, 'updated_at' => new DateTime]
);
// Uncomment the below to run the seeder
DB::table('projects')->insert($projects);
}
}
对于任务表:
public function run()
{
//
$tasks = array(
['id' => 1, 'name' => 'Task 1', 'slug' => 'task-1', 'project_id' => 1, 'completed' => false, 'description' => 'My first task', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 2, 'name' => 'Task 2', 'slug' => 'task-2', 'project_id' => 1, 'completed' => false, 'description' => 'My first task', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 3, 'name' => 'Task 3', 'slug' => 'task-3', 'project_id' => 1, 'completed' => false, 'description' => 'My first task', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 4, 'name' => 'Task 4', 'slug' => 'task-4', 'project_id' => 1, 'completed' => true, 'description' => 'My second task', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 5, 'name' => 'Task 5', 'slug' => 'task-5', 'project_id' => 1, 'completed' => true, 'description' => 'My third task', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 6, 'name' => 'Task 6', 'slug' => 'task-6', 'project_id' => 2, 'completed' => true, 'description' => 'My fourth task', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 7, 'name' => 'Task 7', 'slug' => 'task-7', 'project_id' => 2, 'completed' => false, 'description' => 'My fifth task', 'created_at' => new DateTime, 'updated_at' => new DateTime]
);
//// Uncomment the below to run the seeder
DB::table('tasks')->insert($tasks);
}
}
【问题讨论】:
-
这两个表的迁移情况如何?
-
博文中增加了扩展迁移类。
-
您是第一次运行脚本吗?检查数据库中的表。