跳至主要内容
版本:v6 - 稳定版

使用关联创建

如果所有元素都是新的,则可以通过一步在嵌套关联中创建一个实例。

相反,目前无法执行涉及嵌套对象的更新和删除操作。为此,您必须显式地执行每个单独的操作。

BelongsTo / HasMany / HasOne 关联

考虑以下模型

class Product extends Model {}
Product.init(
{
title: Sequelize.STRING,
},
{ sequelize, modelName: 'product' },
);
class User extends Model {}
User.init(
{
firstName: Sequelize.STRING,
lastName: Sequelize.STRING,
},
{ sequelize, modelName: 'user' },
);
class Address extends Model {}
Address.init(
{
type: DataTypes.STRING,
line1: Sequelize.STRING,
line2: Sequelize.STRING,
city: Sequelize.STRING,
state: Sequelize.STRING,
zip: Sequelize.STRING,
},
{ sequelize, modelName: 'address' },
);

// We save the return values of the association setup calls to use them later
Product.User = Product.belongsTo(User);
User.Addresses = User.hasMany(Address);
// Also works for `hasOne`

可以通过以下方式一步创建新的 ProductUser 和一个或多个 Address

return Product.create(
{
title: 'Chair',
user: {
firstName: 'Mick',
lastName: 'Broadstone',
addresses: [
{
type: 'home',
line1: '100 Main St.',
city: 'Austin',
state: 'TX',
zip: '78704',
},
],
},
},
{
include: [
{
association: Product.User,
include: [User.Addresses],
},
],
},
);

请注意在 Product.create 调用中使用了 include 选项。Sequelize 需要此选项才能理解您尝试与关联一起创建的内容。

注意:这里,我们的用户模型称为 user,其中 u 小写 - 这意味着对象中的属性也应该是 user。如果 sequelize.define 给定的名称为 User,则对象中的键也应为 Useraddresses 也是如此,只是由于它是 hasMany 关联,因此使用了复数形式。

带有别名的 BelongsTo 关联

前面的示例可以扩展为支持关联别名。

const Creator = Product.belongsTo(User, { as: 'creator' });

return Product.create(
{
title: 'Chair',
creator: {
firstName: 'Matt',
lastName: 'Hansen',
},
},
{
include: [Creator],
},
);

HasMany / BelongsToMany 关联

让我们引入将产品与多个标签关联起来的功能。模型设置可能如下所示:

class Tag extends Model {}
Tag.init(
{
name: Sequelize.STRING,
},
{ sequelize, modelName: 'tag' },
);

Product.hasMany(Tag);
// Also works for `belongsToMany`.

现在,我们可以通过以下方式创建具有多个标签的产品:

Product.create(
{
id: 1,
title: 'Chair',
tags: [{ name: 'Alpha' }, { name: 'Beta' }],
},
{
include: [Tag],
},
);

并且,我们可以修改此示例以支持别名:

const Categories = Product.hasMany(Tag, { as: 'categories' });

Product.create(
{
id: 1,
title: 'Chair',
categories: [
{ id: 1, name: 'Alpha' },
{ id: 2, name: 'Beta' },
],
},
{
include: [
{
association: Categories,
as: 'categories',
},
],
},
);