简体   繁体   中英

Get the data from related tables (models) sequelize

Let's say I have these tables:

countries
    id - integer
    name - string

users
    id - integer
    countryId - integer
    name - string

What I want is to get all the users with their country names instead of the country ids... Sequelize docs are good, but confusing...

I got the following func to get all the users:

function get( request, response ) {

    models.users.findAll( {

        order: [ [ request.query.orderBy, request.query.sort ] ]

    } ).then( function ( users ) {

        response.json( users );

    } );

}

And here's my users.js model:

'use strict';
module.exports = function ( sequelize, DataTypes ) {

    var users = sequelize.define( 'users', {
        name: DataTypes.STRING( 50 ),
        countryId: DataTypes.INTEGER,
    }, {
        classMethods: {
            associate: function ( models ) {
                // associations can be defined here
            }
        }
    } );

    return users;

};

So... what do I need to do in order to get the country name instead of the id when querying users model?

User.belongsTo(Country)
User.findAll({ include: [Country] })

Each user will have a .country property, where you can get the name - it's not possible to have the country name added directly to the same object, for that you'll have to use a raw query, or format the result afterwards

You have to first define the association in your models

'use strict';
module.exports = function ( sequelize, DataTypes ) {

var users = sequelize.define( 'users', {
    name: DataTypes.STRING( 50 ),
    countryId: DataTypes.INTEGER,
}, {
    classMethods: {
        associate: function ( models ) {
            users.belongsTo(models.countries, {foreignKey: countryId})
        }
    }
} );

return users;

};

You can then query using include:

models.users.findAll( {

    order: [ [ request.query.orderBy, request.query.sort ] ],
    include: [{
        model: models.countries
    }]
} ).then( function ( users ) {

    // do some formating on the output

} );

After you can format your output if you only want the country_name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM