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();
});