A
A
Arthur2018-09-25 18:45:43
Laravel
Arthur, 2018-09-25 18:45:43

How to delete a post with a many to many link?

Good afternoon.
There are three tables
users
posts
users_posts
The task is to delete the post and the user who created it, knowing only the post id.
I will be glad for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pushkarev, 2018-09-25
@ART_CORP

Do you need to delete a post and a user, or a post and a link?
Deleting a post and a link

$post = Post::findOrFail($id);
$post->user()->sync([]);
$post->delete();

Removing everything
$post = Post::findOrFail($id);
$post->user()->delete();
$post->delete();

Customization via migrations
Schema::create('users_posts', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned()->index();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->integer('post_id')->unsigned()->index();
    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question