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
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)
Most helpful comment
If you're set on not utilizing the junction model, there is a way to do this with
fromJson()and$relatedQuery().(from here)