How to delete post_tags and tag in a same instruction

Published 11 months ago by Lina

Hi friends,

I have this code and I want to do on the best way:

    public function deleteTag(Request $request)
    {
        Tag::find($request->id)->post_tags()->delete();
        return Tag::destroy($request->id);
    }

Delete the post_tags and the tags

post_tags (tag_id, post_id) tags(id, tag_name)

Best Answer (As Selected By Lina)
Dry7

@Lina use foregin keys in migration (and db) and everything will happen automatically

Schema::create('post_tags', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('tag_id', false, true);
    $table->integer('post_id', false, true);

    $table->foreign('tag_id', 'fk__post_tags__tag_id')
               ->references('id')
               ->on('tags')
               ->onDelete('cascade');
    $table->foreign('post_id', 'fk__post_tags__post_id')
               ->references('id')
               ->on('posts')
               ->onDelete('cascade');
});
Dry7
Dry7
11 months ago (151,880 XP)

@Lina use foregin keys in migration (and db) and everything will happen automatically

Schema::create('post_tags', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('tag_id', false, true);
    $table->integer('post_id', false, true);

    $table->foreign('tag_id', 'fk__post_tags__tag_id')
               ->references('id')
               ->on('tags')
               ->onDelete('cascade');
    $table->foreign('post_id', 'fk__post_tags__post_id')
               ->references('id')
               ->on('posts')
               ->onDelete('cascade');
});
Lina

Yes Sir! This is what I was looking for, thank you so much!

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