Creating with Associations - 创建关联

只要所有元素都是新元素,就可以一步创建带有嵌套关联的实例.

相反,无法执行涉及嵌套对象的更新和删除. 为此,你将必须明确执行每个单独的操作.

BelongsTo / HasMany / HasOne 关联

考虑以下模型:

  1. class Product extends Model {}
  2. Product.init({
  3. title: Sequelize.STRING
  4. }, { sequelize, modelName: 'product' });
  5. class User extends Model {}
  6. User.init({
  7. firstName: Sequelize.STRING,
  8. lastName: Sequelize.STRING
  9. }, { sequelize, modelName: 'user' });
  10. class Address extends Model {}
  11. Address.init({
  12. type: DataTypes.STRING,
  13. line1: Sequelize.STRING,
  14. line2: Sequelize.STRING,
  15. city: Sequelize.STRING,
  16. state: Sequelize.STRING,
  17. zip: Sequelize.STRING,
  18. }, { sequelize, modelName: 'address' });
  19. // 我们保存关联设置调用的返回值,以便以后使用
  20. Product.User = Product.belongsTo(User);
  21. User.Addresses = User.hasMany(Address);
  22. // 也适用于 `hasOne`

一个新的 Product,User 和一个或多个 Address 可以按以下步骤一步创建:

  1. return Product.create({
  2. title: 'Chair',
  3. user: {
  4. firstName: 'Mick',
  5. lastName: 'Broadstone',
  6. addresses: [{
  7. type: 'home',
  8. line1: '100 Main St.',
  9. city: 'Austin',
  10. state: 'TX',
  11. zip: '78704'
  12. }]
  13. }
  14. }, {
  15. include: [{
  16. association: Product.User,
  17. include: [ User.Addresses ]
  18. }]
  19. });

观察 Product.create 调用中 include 参数的用法. 这对于 Sequelize 理解与关联一起创建的内容很有必要.

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

一个别名 BelongsTo 关联

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

  1. const Creator = Product.belongsTo(User, { as: 'creator' });
  2. return Product.create({
  3. title: 'Chair',
  4. creator: {
  5. firstName: 'Matt',
  6. lastName: 'Hansen'
  7. }
  8. }, {
  9. include: [ Creator ]
  10. });

HasMany / BelongsToMany 关联

让我们介绍将产品与许多标签关联的功能. 设置模型如下所示:

  1. class Tag extends Model {}
  2. Tag.init({
  3. name: Sequelize.STRING
  4. }, { sequelize, modelName: 'tag' });
  5. Product.hasMany(Tag);
  6. // 也适用于 `belongsToMany`.

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

  1. Product.create({
  2. id: 1,
  3. title: 'Chair',
  4. tags: [
  5. { name: 'Alpha'},
  6. { name: 'Beta'}
  7. ]
  8. }, {
  9. include: [ Tag ]
  10. })

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

  1. const Categories = Product.hasMany(Tag, { as: 'categories' });
  2. Product.create({
  3. id: 1,
  4. title: 'Chair',
  5. categories: [
  6. { id: 1, name: 'Alpha' },
  7. { id: 2, name: 'Beta' }
  8. ]
  9. }, {
  10. include: [{
  11. association: Categories,
  12. as: 'categories'
  13. }]
  14. })