0
votes

How do i access another hasMany in eloquent? There are 3 models: post,comment and upvote. Each post hasMany comment and each comment hasMany upvote.

If I delete the post, i want to delete the comment as well as the comment's upvote.

$post = Post::find ($id);
$post->comment->each->delete() // deletes all the post comment
$post->delete() //delete the post

This works, but how do i delete the comment's upvote ?

$post->comment->upvote->each->delete() // does not work to delete comment's upvote

This does not work. It returns message: "Property [upvote] does not exist on this collection instance."

UPDATE

Below are the table schemes

Post

Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->string('title');
$table->string('desc');
$table->string('category');
$table->integer('total_comment')->default(0);
$table->timestamps();
});

Comment

Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('post_id')->unsigned()->foreign('post_id')->references("id")->on("posts")->onDelete("cascade");
$table->string('comment');
$table->integer('upvote')->default(0);
$table->timestamps();
});

Upvote

Schema::create('upvote', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('comment_id')->unsigned()->foreign('comment_id')->references("id")->on("comments")->onDelete("cascade");
$table->integer('user_id');
$table->timestamps();
});
1
Its better to add `onDelete('cascade') in model migrationShihab EK

1 Answers

1
votes

If your Models are connected by a Foreign Key Constraints,
all post with its related comments & all comments with its related votes will be deleted, but you must include ->onDelete('cascade'); in the tables migration:

Comment table migration

$table->foreign('post_id')
  ->references('id')->on('posts')
  ->onDelete('cascade');

Votes table migration

$table->foreign('comment_id')
  ->references('id')->on('comments')
  ->onDelete('cascade');

Edit:

Another way you can do this is to get the comments of the post then iterate each comment to delete its upvotes:

//Get the requierd post
$post = Post::find ($id);

//Iterate the requierd post comments
foreach ($post->comment as comment){
 //delete each comment upvotes
 comment->each->upvote->delete()
}

//then delete the comments
$post->comment->each->delete() // deletes all the post comment