[英]Sequelize - How do I “select” instances of a model if a relation exists to another model
我在Node.JS應用程序中使用PostgreSQL,並且將SequelizeJS作為ORM使用。 我有以下查詢:
假設我有兩個模型:
User(name,email)
Category(name,createdBy)
Category.createdBy
是引用User.id
的外鍵。這兩個表具有多對多關系:
Category.belongsToMany(models.User, {through: 'UserCategory'});
User.belongsToMany(models.Category, {through: 'UserCategory'});
如果類別與用戶相關聯,則UserCategory表上將存在映射。 否則不會。
如何“選擇”實例以找到我由用戶X創建或與用戶X關聯的所有類別,即(categories associated to user X) + (categories created by user X)
?
默認情況下,Sequelize將向模型實例添加get / set / add / remove方法。
// All categories associated to userId
User.findById(userId).getCategories()
// All categories create by userId
Category.findAll({
where: {
createdBy: userId
}
})
嘗試這個:
Category.belongsToMany(models.User, {through: 'CreateCategory'});
User.belongsToMany(models.Category, {through: 'CreateCategory','foreignKey':'createdBy' });
這將允許您與其他表定義另一個關系,該表存儲了Category
和userId
createdBy
字段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.