我正在尝试使用sequelize ORM进行mysql查询,以选择friends.user_id上的用户名。
到目前为止,我想出了这个解决方案,它的效果不错,但是它选择了AS Users ON Friends.friend_id
而不是AS Users ON Friends.user_id
和关系在这里描述
db.Friends.belongsTo(db.Users, { as: 'UserOpUsers', sourceKey: 'friend_id', foreignKey: 'user_id' })
查询确实
SELECT `Friends`.`id` AS `friend_id`, `Users`.`username`, `Users`.`id`, `Friends`.`status` FROM `wd_friends_relations` AS `Friends` LEFT OUTER JOIN `info_users` AS `Users` ON `Friends`.`friend_id` = `Users`.`id` WHERE `Friends`.`friend_id` = 2;
但应该可以
SELECT `Friends`.`id` AS `friend_id`, `Users`.`username`, `Users`.`id`, `Friends`.`status` FROM `wd_friends_relations` AS `Friends` LEFT OUTER JOIN `info_users` AS `Users` ON `Friends`.`user_id` = `Users`.`id` WHERE `Friends`.`friend_id` = 2;
答案 0 :(得分:0)
belongsTo关联http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-belongsTo中没有sourceKey,它仅存在于HasOne和HasMany关系中。所以使用这样的东西,
db.Friends.belongsTo(db.Users, { as: 'UserOpUsers', foreignKey: 'user_id' })
它将创建这样的查询,
SELECT `Friends`.`id` AS `friend_id`, `Users`.`username`, `Users`.`id`, `Friends`.`status` FROM `wd_friends_relations` AS `Friends` LEFT OUTER JOIN `info_users` AS `Users` ON `Friends`.`user_id` = `Users`.`id` WHERE `Friends`.`friend_id` = 2;