Sequelize association hasOne,belongsTo

Ris*_*vik 15 postgresql orm node.js sequelize.js

问题是我无法使用关系hasOne,它不会急于加载状态类型对象.

所有查询都在现有表上完成.

这是客户表,重要的是这个cst_state_type领域:

module.exports = function(sequelize, DataTypes) {

    return sequelize.define('customer', {

        customer: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            allowNull: true,
            validate: {
                isNumeric: true
            }
        },
        first_name: {
            type: DataTypes.STRING(100),
            validate: {
                isAlphanumeric: true
            }
        },
        last_name: DataTypes.STRING(100),
        identity_code: {
            type: DataTypes.STRING(20),
            allowNull: true,
            validate: {
                isNumeric: true
            }
        },
        note: DataTypes.STRING(1000),
        birth_date: DataTypes.DATE,


        created_by: DataTypes.INTEGER,
        updated_by: DataTypes.INTEGER,

        cst_type: DataTypes.INTEGER,
        cst_state_type:  {
            type: DataTypes.INTEGER,
        }

    }, {
        tableName: 'customer',

        updatedAt: 'updated',
        createdAt: 'created',
        timestamps: true
    });
};
Run Code Online (Sandbox Code Playgroud)

cst_state_type表:

module.exports = function(sequelize, DataTypes) {

    return sequelize.define('StateType', {

        cst_state_type: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true,
            validate: {
            }
        },
        name: DataTypes.STRING(100),
    }, {
        tableName: 'cst_state_type',
        timestamps: false
    });
};
Run Code Online (Sandbox Code Playgroud)

如何描述关系:

  global.db.Customer.hasOne(global.db.StateType, {
    foreignKey: 'cst_state_type',
    as: 'state_type'
  });

  global.db.StateType.belongsTo(global.db.Customer, {
    foreignKey: 'cst_state_type'
  });
Run Code Online (Sandbox Code Playgroud)

并创建急切的加载查询:

    db.Customer.findAll( {
        include: [
            { model: db.Address, as: 'addresses' },
            { model: db.StateType, as: 'state_type' }
        ]
    })
        .success(function (customers) {
            res.json(200, customers);
        })
        .fail(function (error) {
            res.json(500, { msg: error });
        });
Run Code Online (Sandbox Code Playgroud)

Ger*_*ard 23

谢谢你的回答,它给了我很多帮助.您还可以使用classmethods直接在模型中添加关系.我在下面添加了一个例子,希望这有帮助!

用户模型(文件)

module.exports = function(sequelize, DataTypes){
    var User = sequelize.define(
        'User', {
            name: {
                type: DataTypes.STRING,
                allowNull: false
            }
        },
        {
            classMethods:{
                associate:function(models){
                    User.hasMany(models.Comment, { foreignKey: 'userId'} );
                }
            }
        }

    );
    return User;
};
Run Code Online (Sandbox Code Playgroud)

评论模型(文件):

module.exports = function(sequelize, DataTypes){
    var Comment = sequelize.define(
        'Comment', {
            text: {
                type: DataTypes.STRING,
                allowNull: false
            }
        },
        {
            classMethods:{
                associate:function(models){
                    Comment.belongsTo(models.User, { foreignKey:'userId'} );
                }
            }
        }

    );
    return Comment;
};
Run Code Online (Sandbox Code Playgroud)

您不必设置foreignkey,如果您不指定foreignkeys,sequelize将处理它.

然后在查询中:

models.Comment.find({
        where: { id: id },
        include: [
            models.User
        ],
        limit: 1
    })
Run Code Online (Sandbox Code Playgroud)


Jan*_*ier 6

我很确定错误出在您的关联中。根据您描述表结构的方式,关联应如下所示:

global.db.Customer.belongsTo(global.db.StateType, {
    foreignKey: 'cst_state_type',
    as: 'state_type'
});

global.db.StateType.hasMany(global.db.Customer, {
    foreignKey: 'cst_state_type'
});
Run Code Online (Sandbox Code Playgroud)

据我了解,相同的状态可以分配给许多客户,因此StateType.hasMany。来自 customer -> statetype 的关系是一个“反向关联”,这意味着外键在客户表中。为此你需要belongsTo