簡體   English   中英

Sequelize-如果與另一個模型存在關系,如何“選擇”模型的實例

[英]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)

那應該是

myUser = User();
myUser.categories();

看一下如何為續集定義和查詢n:m關系: n:m

默認情況下,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' });

這將允許您與其他表定義另一個關系,該表存儲了CategoryuserId createdBy字段

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM