Reputation: 644
I know how to create the migrations with laravel 5.1 and I have the following code
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');
});
}
When I try to delete a category with articles , I have an error with foreign key , it's anny possibility to drop this category ?
Upvotes: 1
Views: 52
Reputation: 6720
When creating a foreign key constraint, you can also decide what should happen with the constraints. For instance, if you want to delete all articles when a category is deleted (as I guess is your question):
Schema::table('articulos', function($table) {
$table->foreign('categoria_id')->references('id')->on('categorias')->onDelete('cascade');
$table->foreign('creador_id')->references('id')->on('users');
});
Also see documentation. The cascade
identifies to the database that on deletion
of a categorias
entry, the table should cascade
the action into the articulos
table.
To further clarify the options in this foreign constraint, you can use:
onDelete('set null')
to make the column value null once the foreign key is deletedonDelete('restrict')
(default behavior) denies deletion of foreign key if still entries existonDelete('cascade')
to automatically delete entries once the foreign key is deletedMore information for MySQL. Please note that foreign key constraint are not necessary for Laravel to support relations. Sometimes you might not need a foreign key.
Also note aside from the onDelete
you can also use onUpdate
.
Upvotes: 2