sequelize非唯一表/别名

w9apscun  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(269)

迪尔斯遇到了一个问题,因为includejoin一个表抛出另一个表,然后我立即包含它
如果我通过(provider)访问(user)表,则(user)表应返回provider name
如果包含(user)表imddly,则意味着获取客户名称
但我得到下面的错误
er\ Q\ U table:不是唯一的表/别名:“provider.user”
代码:

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']
                }]
            }
        ]
    })
wbgh16ku

wbgh16ku1#

如果要两次包含同一模型,则需要为关系/关联指定别名:

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']
    }]
}]

相关问题