当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 关于Sequelize连接查询时inlude中model和association的区别详解

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

2019年03月23日  | 移动技术网IT编程  | 我要评论

前言

大家都知道在使用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重新定义模型关系。

总结

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网