cphill
cphill

Reputation: 5924

Sequelize Querying Many to Many Relationship and Accessing Object

I have a case where I am querying information from two tables that have a many-to-many relationship with a "through" table. When I make my query it appears that I am querying correctly by not using the "through" table as the table join reference and receiving the outputted records with both table attributes, but I am unable to access the field properties of the joined table. Here is the outputted values.

{"fullNameSlug":"Tester Test","email":"[email protected]","firstName":"Tester","lastName":"Test","teams":[{"teamName":"Sales","member":{"memberId":1,"memberEmail":"[email protected]","organizationId":1,"teamId":1,"userId":1,"created_at":"2016-08-21T21:15:19.000Z","updated_at":"2016-08-21T22:00:32.000Z","organization_id":1,"team_id":1,"user_id":1}}]}

Here is my query and how I am setting the data:

.get(function(req, res){
 models.User.find({
                where: {
                    organizationId: organization.organizationId
                }, attributes: ['email', 'firstName', 'lastName'],
                include: [{ 
                    model: models.Team,
                    attributes: ['teamName']
                }]
            });
        }).then(function(currentUsers){
            res.jsonp(currentUsers);
console.log(currentUsers);
        });

Here is how I was trying to access the teamName in my view: {{currentUsers.teams.teamName}}, which is not returning a value, but {{currentUsers.email}} returns the right user email.

User Table:

module.exports = function(sequelize, DataTypes) {

var User = sequelize.define('user', {
    userId: {
        type: DataTypes.INTEGER,
        field:'user_id',
        autoIncrement: true,
        primaryKey: true
    },
    firstName: {
        type: DataTypes.STRING,
        field: 'first_name'
    },
    lastName: {
        type: DataTypes.STRING,
        field: 'last_name'
    },
    email: {
        type: DataTypes.STRING,
        isEmail: true,
        unique: true,
        set: function(val) {
            this.setDataValue('email', val.toLowerCase());
        }
    },
    password: DataTypes.STRING,
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    }
}, {
    underscored: true,
    freezeTableName: true,
    },
    classMethods: {
        associate: function(db) {
            User.belongsToMany(db.Organization, { through: 'member', foreignKey: 'user_id'}),
            User.belongsToMany(db.Team, { through: 'member', foreignKey: 'user_id'})
        }
});
    return User;
}

Team table:

module.exports = function(sequelize, DataTypes) {

var Team = sequelize.define('team', {
    teamId: {
        type: DataTypes.INTEGER,
        field: 'team_id',
        autoIncrement: true,
        primaryKey: true,
        notNull: true
    },
    teamName: {
        type: DataTypes.STRING,
        field: 'team_name'
    },
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id'
    },
},{
    underscored: true,
    freezeTableName: true,
    classMethods: {
        associate: function(db) {
            Team.belongsToMany(db.User, { through: 'member', foreignKey: 'team_id' });
        },
    }
});
    return Team;
}

Member Table:

module.exports = function(sequelize, DataTypes) {

var Member = sequelize.define('member', {
    memberId: {
        type: DataTypes.INTEGER,
        field: 'member_id',
        autoIncrement: true,
        primaryKey: true
    },
    memberEmail: {
        type: DataTypes.STRING,
        field: 'member_email',
        isEmail: true,
        unique: true
    },
    organizationId: {
        type: DataTypes.INTEGER,
        field: 'organization_id',
        allowNull: true
    },
    teamId: {
        type: DataTypes.INTEGER,
        field: 'team_id',
        allowNull: true
    },
    userId: {
        type: DataTypes.INTEGER,
        field: 'user_id',
        allowNull: true
    }
},{
    underscored: true,
    freezeTableName: true,
});
    return Member;
}

Outputted SQL:

SELECT `user`.*, `teams`.`team_id` AS `teams.teamId`, `teams`.`team_name` AS `teams.teamName`, `teams.member`.`member_id` AS `teams.member.memberId`, `teams.member`.`member_email` AS `teams.member.memberEmail`, `teams.member`.`organization_id` AS `teams.member.organizationId`, `teams.member`.`team_id` AS `teams.member.teamId`, `teams.member`.`user_id` AS `teams.member.userId`, `teams.member`.`created_at` AS `teams.member.created_at`, `teams.member`.`updated_at` AS `teams.member.updated_at`, `teams.member`.`organization_id` AS `teams.member.organization_id`, `teams.member`.`team_id` AS `teams.member.team_id`, `teams.member`.`user_id` AS `teams.member.user_id` FROM (SELECT `user`.`user_id` AS `userId`, `user`.`email`, `user`.`first_name` AS `firstName`, `user`.`last_name` AS `lastName` FROM `user` AS `user` WHERE `user`.`organization_id` = 1 LIMIT 1) AS `user` LEFT OUTER JOIN (`member` AS `teams.member` INNER JOIN `team` AS `teams` ON `teams`.`team_id` = `teams.member`.`team_id`) ON `user`.`userId` = `teams.member`.`user_id`;

Upvotes: 1

Views: 641

Answers (1)

Yrysbek Tilekbekov
Yrysbek Tilekbekov

Reputation: 2775

Consider your relations, User has many Teams trough table Member and your query returns user with many teams(array of team objects) as expected. You should use user.teams[0].teamName to get specific team by key, or loop objects in this array

Upvotes: 1

Related Questions