关于Sequelize连接查询时inlude中model和association的区

大家都知道在使用Sequelize进行关系模型(表)间连接查询时,我们会通过model/as来指定已存在关联关系的连接查询模型,或是通过association来直接指定连接查询模型关系。那么,两者各应该在什么场景下使用呢?

一、 示例准备

模型定义

首先,定义User和Company两个模型:

'use strict' const 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重新定义模型关系。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwzjdy.html