Node.js Sequelize ManyToMany关系产生错误的SQL

时间:2013-02-05 05:09:17

标签: javascript mysql node.js sequelize.js

我对续集ManyToMany关系有疑问。

以下是我的模特......

var db = {

    players: sequelize.define('players', {
        name: Sequelize.STRING
    }),

    teams: sequelize.define('teams', {
        name: Sequelize.STRING
    }),   


    init: function() {

        this.players.hasMany(this.teams, {joinTableName: 'teams_has_players'});
        this.teams.hasMany(this.players, {joinTableName: 'teams_has_players'});

        this.players.sync();
        this.teams.sync();

    }

};

这是查找

db.players.findAll({
    where:      {team_id: 1},
    include:    ['teams']
}).success(function(results) {
    // print the results
});

上面的find会产生以下SQL:

SELECT 
    players . *,
    teams.name AS `teams.name`,
    teams.id AS `teams.id`
FROM
    players
        LEFT OUTER JOIN
    teams_has_players ON teams_has_players.player_id = players.id
        LEFT OUTER JOIN
    teams ON teams.id = teams_has_players.team_id
WHERE
    players.team_id = '1';

这似乎是错误的,WHERE语句应该是WHERE teams.team_id = '1'

我在哪里错了?

提前致谢

1 个答案:

答案 0 :(得分:1)

实际上一切看起来都很好 - 嗯。 db.players.findAll where: { team_id: 1 } WHERE players.team_id = '1'应使用teams创建查询。这完全可以预料到。此外,您team_id将不会有id而是include。但是,{{1}}很有可能被打破。