M K*_*M K 92 php laravel laravel-migrations
无法弄清楚如何在Laravel中的表上设置正确的onDelete约束.(我和SqLite合作)
$table->...->onDelete('cascade'); // works
$table->...->onDelete('null || set null'); // neither of them work
Run Code Online (Sandbox Code Playgroud)
我有3次迁移,创建了gallery表:
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';
});
Run Code Online (Sandbox Code Playgroud)
创建图片表:
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';
});
Run Code Online (Sandbox Code Playgroud)
将图库表链接到图片:
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
});
Run Code Online (Sandbox Code Playgroud)
我没有收到任何错误.此外,即使"级联"选项也不起作用(仅在图库表上).删除图库会删除所有图片.但删除封面图片,不会删除图库(用于测试目的).
由于即使"级联"未被触发,我"设置空"也不是问题.
编辑(解决方法):
阅读完这篇文章之后,我改变了我的架构.现在,图片表包含一个"is_cover"单元格,用于指示此图片是否是其相册的封面.
原始问题的解决方案仍然受到高度赞赏!
Joh*_*han 265
如果要在删除时设置null:
$table->...->onDelete('set null');
Run Code Online (Sandbox Code Playgroud)
首先确保将外键字段设置为可为空:
$table->integer('foreign_id')->unsigned()->nullable();
Run Code Online (Sandbox Code Playgroud)
Aym*_*awy 16
$table->foreignId('forign_id')->nullable()->constrained("table_name")->cascadeOnUpdate()->nullOnDelete();
Run Code Online (Sandbox Code Playgroud)
不同的选项在类中声明Illuminate\Database\Schema\ForeignKeyDefinition(参见源代码)。
根据
http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
$ table-> onDelete('set null')应该可以尝试
$table->...->onDelete(DB::raw('set null'));
Run Code Online (Sandbox Code Playgroud)
如果有任何错误,也会有帮助
| 归档时间: |
|
| 查看次数: |
65152 次 |
| 最近记录: |