我使用laravel migration创建了一个包含父子关系的表树,如下所示:
class CreateTableTree extends Migration
{
public function up()
{
Schema::create('trees', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id')->unsigned();
$table->string('name');
$table->integer('has_child');
$table->integer('depth');
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('trees')->onDelete('cascade');
});
}
public function down()
{
Schema::dropIfExists('trees');
}
}
我想从表中的数据中获取嵌套集合。我上面有一个模型树。
出于测试目的,我想使用这样的播种机插入一些数据:
public function run()
{
for($i=0;$i<5;$i++){
$one = new Tree();
$one->parent_id=0;
$one->name = 'One'.$i;
$one->has_child=1;
$one->depth=0;
$one->save();
for($j=0;$j<3;$j++){
$two = new Tree();
$two->parent_id=$one->id;
$two->name = 'One'.$i.'Two'.$j;
$two->has_child=1;
$two->depth=1;
$two->save();
}
}
}
当我通过artisan命令运行播种机时。我有以下错误:
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`website`.`trees`,
CONSTRAINT `trees_parent_id_foreign` FOREIGN KEY (`parent_id`) REFERENCES `trees` (`id`) ON DELETE CASCADE) (SQL: insert into `trees` (`p arent_id`, `name`, `has_child`, `depth`, `updated_at`, `created_at`) values (0, One0, 1, 0, 2017-05-27 16:29:40, 2017-05-27 16:29:40))
我无法弄清楚我做错了什么? 任何形式的帮助都表示赞赏。
答案 0 :(得分:1)
查询失败,因为表中没有ID = 0,因此您需要使parent_id
字段为空:
$table->integer('parent_id')->unsigned()->nullable();
然后你就可以把它保持为空,只需删除这一行:
$one->parent_id = 0;