5 months ago

Map query hasMany to array

Posted 5 months ago by mleontenko

I have two tables, "posts" and "comments".

One post can have multiple comments:

In Post model:

public function comments()
        return $this->hasMany('App\Comment', 'post_id', 'id');

When I delete Post, I also want to delete related comments, so delete method in controller looks like this:

$post= Post::find($id);

$comments = $post->comments;

The $comments looks like this:

      "created_at":"2020-04-16 08:53:07",
      "updated_at":"2020-04-16 08:53:07"
      "created_at":"2020-04-16 08:53:07",
      "updated_at":"2020-04-16 08:53:07"

What I want is to map comment id's to array named $comment_ids, so I can delete them like this before the post is deleted:

DB::table('comments')->whereIn('id', $comment_ids)->delete();

How can I do this?

Please sign in or create an account to participate in this conversation.