Bookshelf js – Deleting Row and Related Rows in a Many-to-Many Relationship

In this post I would like to show you a best way to destroy a model and related models/collections of many to many relationship records.

What is Bookshelf js

From the authors of Bookshelf, Bookshelf is a JavaScript ORM for Node.js, built on the Knex SQL query builder. Featuring both promise based and traditional callback interfaces, providing transaction support, eager/nested-eager relation loading, polymorphic associations, and support for one-to-one, one-to-many, and many-to-many relations. It is designed to work well with PostgreSQL, MySQL, and SQLite3.

Database Details

I have 3 tables called posts, tags, post_tags.posts table will hold the data posts data, tags table will hold the tags data, post_tags table will hold the relationship data.

posts – id, title, body
tags – id, name,slug
post_tag – tag_id, post_id

Models Details

Below are my two models called for posts and tags table and they are connected with belongsToMany through the belongsToMany table.

Deleting associations and row

Here router is express js router object, on that we have implemented http delete method.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets. Protection Status