本文介绍了sequelize不是唯一的表/别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Dears遇到了一个问题,因为包含的联接表抛出了另一个表,然后我立即将其包含进来
Dears am getting a problem because included join a table throw another table then i include it immediately
(用户)表应该返回提供者名称(如果我访问(用户)表(通过提供者)
The (User) table should return provider name if i access the (User) table through (Provider)
如果不小心包含了(用户)表,这意味着获得客户名称
if included the (User) table imdditly that's mean getting the customer name
但出现以下错误
代码:
models.Order.findOne({
where: {
id: req.params.id
},attributes: ['orderStatus','id','serviceId','providerId','orderDescription',"orderScheduledDate",'userLat','userLng','createdAt'],
include: [
{
model: models.Provider,
attributes: ['id','userId'],
include : [{
model : models.User,
attributes: ['firstName','lastName','phoneNumber']
},{
model : models.User,
attributes: ['phoneNumber']
}]
}
]
})
推荐答案
如果要两次包含相同的模型,则需要为关系/关联分配别名:
Provider.belongsTo/haveMany/any...(User, {as: 'ProviderUser'}); //<------ HERE
Provider.belongsTo/haveMany/any...(User, {as: 'User'}); //<------ HERE
include: [{
model: models.Provider,
attributes: ['id', 'userId'],
include: [{
model: models.User,
as : 'User' //<---------- HERE
attributes: ['firstName', 'lastName', 'phoneNumber']
}, {
model: models.User,
as : 'ProviderUser' //<---------- HERE
attributes: ['phoneNumber']
}]
}]
这篇关于sequelize不是唯一的表/别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!