无法弄清楚如何在 Laravel 中的表上设置正确的 onDelete 约束。 (我正在使用 SqLite)
$table->...->onDelete('cascade'); // works
$table->...->onDelete('null || set null'); // neither of them work
我有 3 次迁移,创建图库表:
Schema::create('galleries', function($table)
{
$table->increments('id');
$table->string('name')->unique();
$table->text('path')->unique();
$table->text('description')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
});
创建图片表:
Schema::create('pictures', function($table)
{
$table->increments('id');
$table->text('path');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->integer('gallery_id')->unsigned();
$table->foreign('gallery_id')
->references('id')->on('galleries')
->onDelete('cascade');
$table->timestamps();
$table->engine = 'InnoDB';
});
将图库表链接到图片:
Schema::table('galleries', function($table)
{
// id of a picture that is used as cover for a gallery
$table->integer('picture_id')->after('description')
->unsigned()->nullable();
$table->foreign('picture_id')
->references('id')->on('pictures')
->onDelete('cascade || set null || null'); // neither of them works
});
我没有收到任何错误。此外,即使“级联”选项也不起作用(仅在图库表上)。删除图库会删除所有图片。但删除封面图片不会删除图库(用于测试目的)。
由于即使“级联”也没有触发,所以我“设置空”不是问题。
编辑(解决方法):
读完这篇文章后article http://www.codeproject.com/Articles/38655/Prevent-Circular-References-in-Database-Design我稍微改变了我的架构。现在,图片表包含一个“is_cover”单元格,指示该图片是否是其专辑的封面。
原始问题的解决方案仍然受到高度赞赏!