如何只删除 table 相关的
How to delete only the table relationed
我知道如何使用 laravel 5.1 创建迁移并且我有以下代码
public function up()
{
Schema::create('articulos', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->integer('categoria_id')->unsigned();
$table->integer('creador_id')->unsigned();
$table->string('slug', 32);
$table->timestamps();
});
Schema::table('articulos', function($table) {
$table->foreign('categoria_id')->references('id')->on('categorias');
$table->foreign('creador_id')->references('id')->on('users');
});
}
当我尝试删除包含文章的类别时,我遇到外键错误,是否有可能删除此类别?
创建外键约束时,您还可以决定约束应该发生什么。例如,如果您想在删除一个类别时删除所有文章(我猜这是您的问题):
Schema::table('articulos', function($table) {
$table->foreign('categoria_id')->references('id')->on('categorias')->onDelete('cascade');
$table->foreign('creador_id')->references('id')->on('users');
});
另见 documentation。 cascade
向数据库标识 categorias
条目的 on deletion
,table 应该 cascade
将操作放入 articulos
table.
要进一步阐明此外部约束中的选项,您可以使用:
onDelete('set null')
删除外键后使列值为空
onDelete('restrict')
(默认行为)如果仍然存在条目则拒绝删除外键
onDelete('cascade')
删除外键后自动删除条目
有关 MySQL 的更多信息。请注意,Laravel 不需要外键约束来支持关系。有时您可能不需要外键。
另请注意,除了 onDelete
,您还可以使用 onUpdate
。
我知道如何使用 laravel 5.1 创建迁移并且我有以下代码
public function up()
{
Schema::create('articulos', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->integer('categoria_id')->unsigned();
$table->integer('creador_id')->unsigned();
$table->string('slug', 32);
$table->timestamps();
});
Schema::table('articulos', function($table) {
$table->foreign('categoria_id')->references('id')->on('categorias');
$table->foreign('creador_id')->references('id')->on('users');
});
}
当我尝试删除包含文章的类别时,我遇到外键错误,是否有可能删除此类别?
创建外键约束时,您还可以决定约束应该发生什么。例如,如果您想在删除一个类别时删除所有文章(我猜这是您的问题):
Schema::table('articulos', function($table) {
$table->foreign('categoria_id')->references('id')->on('categorias')->onDelete('cascade');
$table->foreign('creador_id')->references('id')->on('users');
});
另见 documentation。 cascade
向数据库标识 categorias
条目的 on deletion
,table 应该 cascade
将操作放入 articulos
table.
要进一步阐明此外部约束中的选项,您可以使用:
onDelete('set null')
删除外键后使列值为空onDelete('restrict')
(默认行为)如果仍然存在条目则拒绝删除外键onDelete('cascade')
删除外键后自动删除条目
有关 MySQL 的更多信息。请注意,Laravel 不需要外键约束来支持关系。有时您可能不需要外键。
另请注意,除了 onDelete
,您还可以使用 onUpdate
。