Skip to content

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

Last updated on November 21, 2022

In this post, I would like to show you the 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, and post_tags.posts table will hold the data post data, the 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.

const Post = bookshelf.Model.extend({
  tableName: 'posts',
  tags: function () {
    return this.belongsToMany(Tags,'post_tag');
  },
});

const Tag = bookshelf.Model.extend({
  tableName: 'tags',
  posts: function() {
    return this.belongsToMany(Post,'post_tag');
  }
});

Deleting associations and row

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

router.delete('/', function (req, res, next) {
  Post.forge({ id: req.body.id }).fetch({ withRelated: ['tags'] }).then(function (post) {
    if (!posts) {
      return res.status(404).json({ error: true, message: 'post not found' })
    }
    // remove all the associations 
    post.tags().detach();
    // delete the post
    post.destroy();
    return res.json({ error: false, message: 'post deleted' });
  }).catch(function (err) {
    res.status(500).json({ error: true, data: { message: err.message } });
  });
});
0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments