Reputation: 241
I am still learning Laravel and run into an issue when I want to remove a record from the database. Most likely I am missing something simple.
I have a tweet migration that looks like this:
public function up()
{
Schema::create('tweets', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('user_id');
$table->string('body');
$table->timestamps();
});
}
There is also a likes-migration hat looks like this:
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('user_id')->constrained()->cascadeOnDelete;
$table->foreignId('tweet_id')->constrained()->cascadeOnDelete;
$table->boolean('liked');
$table->timestamps();
$table->unique(['user_id', 'tweet_id']);
});
}
When in tinker I say
$tweet->delete();
it will delete the tweet-record only when it has no likes. If the tweet has likes, I get the error:
Illuminate/Database/QueryException with message 'SQLSTATE[23000]: Integrity constraint violation : 1451 Cannot delete or update a parrent row: a foreign key constraint fails...."
I think I make a very basic error in teh migration, but I don't know which.
Who can advise?
Kind regards,
Hubert
Upvotes: 1
Views: 283
Reputation: 1
->cascadeOnUpdate()
is a correct helper method (which is a substitute for ->onUpdate('cascade')
as suggested by others) but it looks like you forgot the brackets. If you correct it to the following, it should work:
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('tweet_id')->constrained()->cascadeOnDelete();
$table->boolean('liked');
$table->timestamps();
$table->unique(['user_id', 'tweet_id']);
});
}
Upvotes: 0
Reputation: 18986
When you delete a model that has a foreign key associated with it you have to cleanup. You want to cascade it, your syntax seems off, i'm not sure if it is an alternative way. Normally you would do it like so.
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->foreign('tweet_id')
->references('id')->on('tweets')
->onDelete('cascade');
A newer version of the on delete cascade can be.
$table->foreignId('user_id')
->constrained()
->onDelete('cascade');
Upvotes: 1