sequelize 预加载——迹忆客-ag捕鱼王app官网
如sequelize 关联 这篇文章中简要提到的,预先加载是一次查询多个模型(一个"主"模型和一个或多个关联模型)的数据的行为。 在 sql 级别上,这是具有一个或多个 join 的查询。
完成此操作后,sequelize 将在返回的对象中将适当关联的模型添加到适当命名的自动创建的字段中。
在 sequelize 中,主要通过在模型查找器查询中使用 include 参数(例如,findone, findall 等)来完成预先加载。
基本示例
让我们假设以下设置:
const user = sequelize.define('user', { name: datatypes.string }, { timestamps: false });
const task = sequelize.define('task', { name: datatypes.string }, { timestamps: false });
const tool = sequelize.define('tool', {
name: datatypes.string,
size: datatypes.string
}, { timestamps: false });
user.hasmany(task);
task.belongsto(user);
user.hasmany(tool, { as: 'instruments' });
获取单个关联元素
首先,让我们用其关联的用户加载所有任务:
const tasks = await task.findall({ include: user });
console.log(json.stringify(tasks, null, 2));
输出:
[{
"name": "a task",
"id": 1,
"userid": 1,
"user": {
"name": "john doe",
"id": 1
}
}]
这里,tasks[0].user instanceof user
是 true。 这表明,当 sequelize 提取关联的模型时,它们将作为模型实例添加到输出对象。
上面,在获取的任务中,关联的模型被添加到名为 user 的新字段中。 sequelize 会根据关联模型的名称自动选择此字段的名称,在适用的情况下(即关联为 hasmany 或 belongstomany)使用该字段的复数形式。 换句话说,由于 task.belongsto(user)
导致一项任务与一个用户相关联,因此逻辑选择是单数形式(sequelize 自动遵循该形式)。
获取所有关联的元素
现在,我们将执行相反的操作,而不是加载与给定任务关联的用户,我们将找到与给定用户关联的所有任务。
方法调用本质上是相同的。 唯一的区别是,现在在查询结果中创建的额外字段使用复数形式(在这种情况下为 tasks),其值是任务实例的数组(而不是上面的单个实例)。
const users = await user.findall({ include: task });
console.log(json.stringify(users, null, 2));
输出:
[{
"name": "john doe",
"id": 1,
"tasks": [{
"name": "a task",
"id": 1,
"userid": 1
}]
}]
注意 :由于关联是一对多的,因此访问器(结果实例中的tasks属性)是复数的。
获取别名关联
如果关联是别名的(使用as参数),则在包含模型时必须指定此别名。 与其直接将模型传递给 include 参数,不如为对象提供两个选项:model 和 as。
注意上面的用户的 tool 是如何被别名为 instruments 的。 为了实现这一点,你必须指定要加载的模型以及别名:
const users = await user.findall({
include: { model: tool, as: 'instruments' }
});
console.log(json.stringify(users, null, 2));
输出:
[{
"name": "john doe",
"id": 1,
"instruments": [{
"name": "scissor",
"id": 1,
"userid": 1
}]
}]
你也可以包括指定的关联别名相匹配的字符串:
user.findall({ include: 'instruments' }); // 也可以正常使用
user.findall({ include: { association: 'instruments' } }); // 也可以正常使用
需要预先加载
预先加载时,我们可以强制查询仅返回具有关联模型的记录,从而有效地将查询从默认的 outer join 转为 inner join。 这是通过 required: true
参数完成的,如下所示:
user.findall({
include: {
model: task,
required: true
}
});
此参数也适用于嵌套包含。
在模型级别的预先加载过滤
预先加载时,我们还可以使用 where 参数过滤关联的模型,如以下示例所示:
user.findall({
include: {
model: tool,
as: 'instruments'
where: {
size: {
[op.ne]: 'small'
}
}
}
});
生成 sql:
select
`user`.`id`,
`user`.`name`,
`instruments`.`id` as `instruments.id`,
`instruments`.`name` as `instruments.name`,
`instruments`.`size` as `instruments.size`,
`instruments`.`userid` as `instruments.userid`
from `users` as `user`
inner join `tools` as `instruments` on
`user`.`id` = `instruments`.`userid` and
`instruments`.`size` != 'small';
请注意,上面生成的 sql 查询将仅获取具有至少一个符合条件(在这种情况下为 small)的工具的用户。 出现这种情况是因为,当在 include 内使用 where 参数时,sequelize 会自动将 required 参数设置为 true。 这意味着,将执行 inner join 而不是 outer join,仅返回具有至少一个匹配子代的父代模型。
还要注意,使用的 where 参数已转换为 inner join 的 on 子句的条件。 为了获得 顶层 的 where 子句,而不是 on 子句,必须做一些不同的事情。接下来将展示。
参考其他列
如果你想在包含模型中应用 where 子句来引用关联模型中的值,则可以简单地使用 sequelize.col 函数,如以下示例所示:
// 查找所有具有至少一项任务的项目,其中 task.state === project.state
project.findall({
include: {
model: task,
where: {
state: sequelize.col('project.state')
}
}
})
顶层的复杂 where 子句
为了获得涉及嵌套列的顶级 where 子句,sequelize 提供了一种引用嵌套列的方法:'$nested.column$'
语法。
例如:它可以用于将 where 条件从包含的模型从 on 条件移动到顶层的 where 子句。
user.findall({
where: {
'$instruments.size$': { [op.ne]: 'small' }
},
include: [{
model: tool,
as: 'instruments'
}]
});
生成 sql:
select
`user`.`id`,
`user`.`name`,
`instruments`.`id` as `instruments.id`,
`instruments`.`name` as `instruments.name`,
`instruments`.`size` as `instruments.size`,
`instruments`.`userid` as `instruments.userid`
from `users` as `user`
left outer join `tools` as `instruments` on
`user`.`id` = `instruments`.`userid`
where `instruments`.`size` != 'small';
$nested.column$
语法也适用于嵌套了多个级别的列,例如 $some.super.deeply.nested.column$
。 因此,你可以使用它对深层嵌套的列进行复杂的过滤。
为了更好地理解内部的 where 参数(在 include 内部使用)和使用与不使用 required 参数与使用 $nested.column$
语法的顶级 where 之间的所有区别,下面我们为你提供四个示例:
// inner where, 默认使用 `required: true`
await user.findall({
include: {
model: tool,
as: 'instruments',
where: {
size: { [op.ne]: 'small' }
}
}
});
// inner where, `required: false`
await user.findall({
include: {
model: tool,
as: 'instruments',
where: {
size: { [op.ne]: 'small' }
},
required: false
}
});
// 顶级 where, 默认使用 `required: false`
await user.findall({
where: {
'$instruments.size$': { [op.ne]: 'small' }
},
include: {
model: tool,
as: 'instruments'
}
});
// 顶级 where, `required: true`
await user.findall({
where: {
'$instruments.size$': { [op.ne]: 'small' }
},
include: {
model: tool,
as: 'instruments',
required: true
}
});
生成 sql:
-- inner where, 默认使用 `required: true`
select [...] from `users` as `user`
inner join `tools` as `instruments` on
`user`.`id` = `instruments`.`userid`
and `instruments`.`size` != 'small';
-- inner where, `required: false`
select [...] from `users` as `user`
left outer join `tools` as `instruments` on
`user`.`id` = `instruments`.`userid`
and `instruments`.`size` != 'small';
-- 顶级 where, 默认使用 `required: false`
select [...] from `users` as `user`
left outer join `tools` as `instruments` on
`user`.`id` = `instruments`.`userid`
where `instruments`.`size` != 'small';
-- 顶级 where, `required: true`
select [...] from `users` as `user`
inner join `tools` as `instruments` on
`user`.`id` = `instruments`.`userid`
where `instruments`.`size` != 'small';
使用 right outer join 获取 (仅限 mysql, mariadb, postgresql 和 mssql)
默认情况下,关联是使用 left outer join 加载的 - 也就是说,它仅包含来自父表的记录。 如果你使用的方言支持,你可以通过传递 right 选项来将此行为更改为 right outer join
。
当前, sqlite 不支持 right joins
。
注意: 仅当 required 为 false 时才遵循 right。
user.findall({
include: [{
model: task // 将创建一个 left join
}]
});
user.findall({
include: [{
model: task,
right: true // 将创建一个 right join
}]
});
user.findall({
include: [{
model: task,
required: true,
right: true // 没有效果, 将创建一个 inner join
}]
});
user.findall({
include: [{
model: task,
where: { name: { [op.ne]: 'empty trash' } },
right: true // 没有效果, 将创建一个 inner join
}]
});
user.findall({
include: [{
model: tool,
where: { name: { [op.ne]: 'empty trash' } },
required: false // 将创建一个 left join
}]
});
user.findall({
include: [{
model: tool,
where: { name: { [op.ne]: 'empty trash' } },
required: false
right: true // 将创建一个 right join
}]
});
多次预先加载
include 参数可以接收一个数组,以便一次获取多个关联的模型:
foo.findall({
include: [
{
model: bar,
required: true
},
{
model: baz,
where: /* ... */
},
qux // { model: qux } 的简写语法在这里也适用
]
})
多对多关系的预先加载
当你对具有 "多对多" 关系的模型执行预先加载时,默认情况下,sequelize 也将获取联结表数据。 例如:
const foo = sequelize.define('foo', { name: datatypes.text });
const bar = sequelize.define('bar', { name: datatypes.text });
foo.belongstomany(bar, { through: 'foo_bar' });
bar.belongstomany(foo, { through: 'foo_bar' });
await sequelize.sync();
const foo = await foo.create({ name: 'foo' });
const bar = await bar.create({ name: 'bar' });
await foo.addbar(bar);
const fetchedfoo = await foo.findone({ include: bar });
console.log(json.stringify(fetchedfoo, null, 2));
输出:
{
"id": 1,
"name": "foo",
"bars": [
{
"id": 1,
"name": "bar",
"foo_bar": {
"fooid": 1,
"barid": 1
}
}
]
}
请注意,每个预先加载到 bars 属性中的 bar 实例都有一个名为 foo_bar 的额外属性,它是联结模型的相关 sequelize 实例。 默认情况下,sequelize 从联结表中获取所有属性,以构建此额外属性。
然而,你可以指定要获取的属性。 这是通过在包含的 through 参数中应用 attributes 参数来完成的。 例如:
foo.findall({
include: [{
model: bar,
through: {
attributes: [/* 在此处列出所需的属性 */]
}
}]
});
如果你不需要联结表中的任何内容,则可以在 include 选项的 through 内显式地为 attributes 参数提供一个空数组,在这种情况下,将不会获取任何内容,甚至不会创建额外的属性:
foo.findone({
include: {
model: bar,
through: {
attributes: []
}
}
});
输出:
{
"id": 1,
"name": "foo",
"bars": [
{
"id": 1,
"name": "bar"
}
]
}
每当包含 "多对多" 关系中的模型时,也可以在联结表上应用过滤器。 这是通过在 include 的 through 参数中应用 where 参数来完成的。 例如:
user.findall({
include: [{
model: project,
through: {
where: {
// 这里,`completed` 是联结表上的一列
completed: true
}
}
}]
});
生成 sql (使用 sqlite):
select
`user`.`id`,
`user`.`name`,
`projects`.`id` as `projects.id`,
`projects`.`name` as `projects.name`,
`projects->user_project`.`completed` as `projects.user_project.completed`,
`projects->user_project`.`userid` as `projects.user_project.userid`,
`projects->user_project`.`projectid` as `projects.user_project.projectid`
from `users` as `user`
left outer join `user_projects` as `projects->user_project` on
`user`.`id` = `projects->user_project`.`userid`
left outer join `projects` as `projects` on
`projects`.`id` = `projects->user_project`.`projectid` and
`projects->user_project`.`completed` = 1;
包括所有关联模型
要包括所有关联的模型,可以使用 all 和 nested 参数:
// 提取与用户关联的所有模型
user.findall({ include: { all: true }});
// 递归获取与用户及其嵌套关联关联的所有模型
user.findall({ include: { all: true, nested: true }});
包括软删除的记录
如果你想加载软删除的记录,可以通过将 include.paranoid
设置为 false 来实现:
user.findall({
include: [{
model: tool,
as: 'instruments',
where: { size: { [op.ne]: 'small' } },
paranoid: false
}]
});
排序预先加载的关联
当你想将 order 子句应用于预先加载的模型时,必须对扩展数组使用顶层 order 参数,从要排序的嵌套模型开始。
通过示例可以更好地理解这一点。
company.findall({
include: division,
order: [
// 我们从要排序的模型开始排序数组
[division, 'name', 'asc']
]
});
company.findall({
include: division,
order: [
[division, 'name', 'desc']
]
});
company.findall({
// 如果包含使用别名...
include: { model: division, as: 'div' },
order: [
// ...我们在排序数组的开头使用来自 `include` 的相同语法
[{ model: division, as: 'div' }, 'name', 'desc']
]
});
company.findall({
// 如果我们包含嵌套在多个级别中...
include: {
model: division,
include: department
},
order: [
// ... 我们在排序数组的开头复制需要的 include 链
[division, department, 'name', 'desc']
]
});
对于多对多关系,你还可以按联结表中的属性进行排序。例如:假设我们在 division 和 department 之间存在多对多关系,联结模型为 departmentdivision, 你可以这样:
company.findall({
include: {
model: division,
include: department
},
order: [
[division, departmentdivision, 'name', 'asc']
]
});
在以上所有示例中,大家已经注意到在顶层使用了 order 参数。 但是在 separate: true
时,order 也可以在 include 参数中使用。 在这种情况下,用法如下:
// 这仅能用于 `separate: true` (反过来仅适用于 hasmany 关系).
user.findall({
include: {
model: post,
separate: true,
order: [
['createdat', 'desc']
]
}
});
嵌套的预先加载
你可以使用嵌套的预先加载来加载相关模型的所有相关模型:
const users = await user.findall({
include: {
model: tool,
as: 'instruments',
include: {
model: teacher,
include: [ /* ... */ ]
}
}
});
console.log(json.stringify(users, null, 2));
输出:
[{
"name": "john doe",
"id": 1,
"instruments": [{ // 1:m 和 n:m 关联
"name": "scissor",
"id": 1,
"userid": 1,
"teacher": { // 1:1 关联
"name": "jimi hendrix"
}
}]
}]
这将产生一个外部连接。 但是,相关模型上的 where 子句将创建内部联接,并且仅返回具有匹配子模型的实例。 要返回所有父实例,你应该添加 required: false
。
user.findall({
include: [{
model: tool,
as: 'instruments',
include: [{
model: teacher,
where: {
school: "woodstock music school"
},
required: false
}]
}]
});
上面的查询将返回所有用户及其所有乐器,但仅返回与 woodstock music school 相关的那些老师。
使用带有 include 的 findandcountall
findandcountall
实用功能支持 include。 仅将标记为 required 的 include 项视为 count。 例如:如果你要查找并统计所有拥有个人资料的用户:
user.findandcountall({
include: [
{ model: profile, required: true }
],
limit: 3
});
因为 profile 的 include 已设置为 required,它将导致内部联接,并且仅统计具有个人资料的用户。 如果我们从包含中删除 required,则包含和不包含配置文件的用户都将被计数。 在 include 中添加一个 where 子句会自动使它成为 required:
user.findandcountall({
include: [
{ model: profile, where: { active: true } }
],
limit: 3
});
上面的查询仅会统计拥有有效个人资料的用户,因为当你在 include 中添加 where 子句时,required 会隐式设置为 true。