首页 > 多表关联为何sequelize 的 attributes不生效?

多表关联为何sequelize 的 attributes不生效?

有 user表,role表,然后user和role建立了多对多的关系
代码是这样的

let user = await models.User.findOne({
    where: {id: id},
    attributes: ['name','id']
});
let roles = await user.getRoles({
    attributes: ['name','id'],
    raw: true
});

user和role数据都是能取到的,user 的 attributes也是生效的,
但是roles 的就不行了,role表本身的字段能过滤,但是不知道为什么一定会带上user与role 的关系数据

大概就是我想要的是这样的数据

{ 
    id: 1,
    name: '管理员'
}

却给了我这样的数据

{ 
    id: 1,
    name: '管理员',
    'userRole.createdAt': 2016-09-02T09:43:07.714Z,
    'userRole.updatedAt': 2016-09-02T09:43:07.714Z,
    'userRole.userId': 1,
    'userRole.roleId': 1 
}

看文档也没找到解决的办法
http://docs.sequelizejs.com/e...


你啥也不交待,你数据库用的啥?你用的什么组件来连数据库?都说说,还有getRoles这是个啥?

每个数据库每个组件的操作方法各有区别


这个我帮不了你,后端我主要用 C#,对 NodeJS 不熟


查看一下最终的SQL语句,应该是使用的inner join,所以需要取消inner join。官方文档http://docs.sequelizejs.com/en/latest/api/model/:

Where clauses to apply to the child models. Note that this converts the eager load to an inner join, unless you explicitly set required: false

参考:


我用的是type, 替换了你role里面的name,你的问题是因为user.getRoles最终会转变成为

 SELECT `role`.`type`, `role`.`id`, `userrole`.`id` AS `userrole.id`, `userrole`.`userId` AS `userrole.userId`, `userrole`.`roleId` AS `userrole.roleId`, `userrole`.`createdAt` AS `userrole.createdAt`, `userrole`.`updatedAt` AS `userrole.updatedAt` FROM `roles` AS `role` INNER JOIN `userroles` AS `userrole` ON `role`.`id` = `userrole`.`roleId` AND `userrole`.`userId` = 1;

你写的attribute只能控制role表的输出,不能控制userRole表的输出,这是sequelize的一个问题,但是你可以绕过去, 如下

let roleInstances = await user.getRoles({
    attributes: ['type','id']
});

const roles = roleInstances.map(role => ({ type: role.get('type'), id: role.get('id') }))

// roles = [ { type: 'admin', id: 1 } ]

就可以拿到你想要的结果了,希望对你有帮助

【热门文章】
【热门文章】