3

我在处理多对多关系时遇到问题。

这是我的模型...

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'

我哪里错了?

提前致谢

4

1 回答 1

1

嗯,实际上一切看起来都还不错。db.players.findAllwithwhere: { team_id: 1 }应该用WHERE players.team_id = '1'. 这是完全可以预料的。此外,你teams不会有一个team_id,而是一个id。但是,很有可能include是 atm 坏了。

于 2013-02-05T06:06:11.893 回答