Objection.js: Question: How can I delete from the middle table of a Many-to-Many relationship

Created on 14 Sep 2018  路  4Comments  路  Source: Vincit/objection.js

Hi, I have this case:

Books (id, name)
UserBooks (book.id, user.id)
User (id, name)

I would like to delete a book from a user, I have defined a model for Book, and a model for User, each with a ManyToMany relationship though UserBooks, is there a way I can delete the UserBook from the User model without querying the user first?

I'm aware of unrelate, but I have to query the User first, then use $relatedQuery to delete the UserBooks.

Thanks

Most helpful comment

If you're set on not utilizing the junction model, there is a way to do this with fromJson() and $relatedQuery().

const article = Article.fromJson({ id }, { skipValidation: true });

await article.$relatedQuery('favoritedBy', txn).unrelate().where({ id: currentUserId });

(from here)

All 4 comments

You can create a model for the UserBooks table and simply delete rows from that.

For example:

UserBooks.query().delete().where('userId', 1)

or

UserBooks.query().delete().where('userId', 636).andWhere('bookId', 123)

That would do it, Thanks!

If you're set on not utilizing the junction model, there is a way to do this with fromJson() and $relatedQuery().

const article = Article.fromJson({ id }, { skipValidation: true });

await article.$relatedQuery('favoritedBy', txn).unrelate().where({ id: currentUserId });

(from here)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zuck picture zuck  路  4Comments

sgangwisch picture sgangwisch  路  4Comments

bsdo64 picture bsdo64  路  3Comments

chen7david picture chen7david  路  3Comments

AhmadRaza786 picture AhmadRaza786  路  3Comments