2017-08-02 49 views
0

我已经从用户表中创建了两个外键。续集多个外键仅包含一列

`db.Subscription.belongsTo(db.User, {foreignKey: 'creatorId'}); 
db.Subscription.belongsTo(db.User, {foreignKey: 'subscriberId'});` 

搜索查询过程中出现了包括代替creatorId Subscription.findAll({ where: { subscriberId: req.decoded._idsubscriberId列在这里输入 }, include: [ {model: User, foreignKey: 'creatorId', attributes: ['name', 'role', 'uid', 'imageUrl']}] })

代码有人可以找出我在做什么错在这里。

回答

0

尝试为关联设置一个名称,以便Sequelize具有更好的想法以包含哪个关联。你可以做这样的事情上设置的关联的名字......

db.Subscription.belongsTo(db.User, { 
    as: 'creator', 
    foreignKey: 'creatorId' 
}); 

db.Subscription.belongsTo(db.User, { 
    as: 'subscriber', 
    foreignKey: 'subscriberId' 
}); 

然后你可以使用这些名称的查询来获取特定的关联,因为这样...

Subscription.findAll({ 
    include: { 
    model: User, 
    as: 'creator', 
    attributes: ['name', 'role', 'uid', 'imageUrl'] 
    }, 
    where: { 
    subscriberId: req.decoded._identer 
    } 
}); 

当多次关联到同一个表时,设置名称可帮助ORM确定要加载的关联。对于记录,对于所有返回的记录,您可以通过访问实例上的.creator来访问该关联。

祝你好运! :)

+0

非常感谢迪兰它的工作。 :) –