兰州网站建设|兰州网站制作|兰州网站设计公司|兰州网络公司,中国陕西省住房城乡建设厅官网,青岛网络公司老板是谁,网站色调前言大家都知道在使用Sequelize进行关系模型(表)间连接查询时#xff0c;我们会通过model/as来指定已存在关联关系的连接查询模型#xff0c;或是通过association来直接指定连接查询模型关系。那么#xff0c;两者各应该在什么场景下使用呢#xff1f;一、 示例准备模型定义…前言大家都知道在使用Sequelize进行关系模型(表)间连接查询时我们会通过model/as来指定已存在关联关系的连接查询模型或是通过association来直接指定连接查询模型关系。那么两者各应该在什么场景下使用呢一、 示例准备模型定义首先定义User和Company两个模型use strictconst Sequelize require(sequelize);// 创建 sequelize 实例const sequelize new Sequelize(db1, root, 111111, {logging: console.log});// 定义User模型var User sequelize.define(user, {id:{type: Sequelize.BIGINT(11), autoIncrement:true, primaryKey : true, unique : true},name: { type: Sequelize.STRING, comment:姓名 },sex: { type: Sequelize.INTEGER, allowNull: false, defaultValue: 0, comment:性别 },companyId: { type: Sequelize.BIGINT(11), field: company_id, allowNull: false, comment:所属公司 },isManager: { type: Sequelize.BOOLEAN, field: is_manager, allowNull: false, defaultValue: false, comment:是否管理员}},{ charset: utf8,collate: utf8_general_ci});// 定义Company模型var Company sequelize.define(company, {id:{ type:Sequelize.BIGINT(11), autoIncrement:true, primaryKey : true, unique : true},name: { type: Sequelize.STRING, comment:公司名称 }},{ charset: utf8,collate: utf8_general_ci});// 定义User-Company关联关系User.belongsTo(Company, {foreignKey:companyId});// sequelize.sync({force:true}).then(() {// process.exit();// });如上所示我们定义了User和Company两个模型并通过belongsTo指定了User-Company之间为1:1关系。插入数据接下来基于刚定义的关系模型插入一些测试数据Company.create({name:某公司}).then((result) {return Promise.all([User.create({name:何民三, sex:1, companyId:result.id, isManager: true}),User.create({name:张老二, sex:1, companyId:result.id})])}).then((result) {console.log(done);}).catch((err) {console.error(err);});二、使用model/as在进行连接查询时如果已经定义模型间的关联关系。就可以在inlude查询选项中通过model属性指定要连接查询的模型还可以通过as属性指定别名。如从User模型中查询一个用户并查询该用户所在的公司信息var include [{model: Company,as: company}];User.findOne({include:include}).then((result) {console.log(result.name 是 result.company.name 的员工);}).catch((err) {console.error(err);});查询结果如下何民三 是 某公司 的员工三、使用association连接查询时如果要连接查询的两个模型间事先没有定义连接关系或者要使用定义之外的连接关系。这时可以通过association来定义或重新定义模型关系。如查询Company模型中的任意一个公司并查询该公司的管理员var include [{association: Company.hasOne(User, {foreignKey:companyId, as:manager}),where: {isManager:true}}]Company.findOne({include:include}).then((result) {console.log(result.name 的管理员是 result.manager.name);}).catch((err) {console.error(err);});由于Company-User之间并没有事先定义模型关系因此需要在inlude选项中指定连接查询时所要使用的关联关系。查询结果如下某公司 的管理员是 何民三association除了用于指定之前没有定义的模型关系还可以用于重新用于定义模型关系。如假设我们通过hasMany事先定义了Company-User之间存在1:N的关系。这种关系适用于查询公司下的所有员工。而上例中我们需要通过1:1关系来查公司的管理员因此这时可以通过association重新定义模型关系。总结以上就是这篇文章的全部内容了希望本文的内容对大家的学习或者工作能带来一定的帮助如果有疑问大家可以留言交流谢谢大家对脚本之家的支持。