Skip to content

Documentation: updating associations #9678

Closed

Description

@mschipperheyn

Given something like

export default (sequelize, DataTypes) => {
  const User = sequelize.define(
    'User',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
        lowercase: true
      },
      email: {
        type: DataTypes.STRING(255),
        required: true,
        lowercase: true,
        trim: true
      },
      password: {
        type: DataTypes.STRING(255)
      },
    },
    {
      tableName: 'Users',
      timestamps: true,
    }
  );

  User.associate = models => {
    User.hasMany(models.Address, {
      foreignKey: 'userId',
      as: 'addresses'
      onDelete: 'cascade'
    });
  };

  User.prototype.toJSON = function toJSON() {
    const values = { ...this.get() };
    delete values.password;
    return values;
  };

  return User;
};
{
   email: [email protected]',
   addresses: [
      {
           street: 'Navy street'',
           houseNumber: 10
      },
      {
           id: 55,
           street: 'Main street'',
           houseNumber: 10
      }
   ]
}

I'm having some difficulties understanding how updating an existing association is supposed to work and the documentation doesn't offer help.
I see the following scenarios

  • Inserting a record in a 1-n relation
  • Inserting a record in a 1-1 relation
  • Updating a record in a 1-n relation
  • Updating a record in a 1-1 relation
  • Deleting a record in a 1-n relation

What are you doing?

I tried a simple update, but that doesn't touch the associated record. I tried upsert and it didnt seem to execute any sql. I'm sure I'm doing something wrong here.
I tried simply inserting the associations in a separate call to Sequelize using a single transaction. That works but is inelegant and inflexible (adding an association should imho just impact the model level).

const currentItemDb = await User.get(securityObj, id, {
    include: [
      {
        model: Address,
        as: 'adresses'
      }
    ]
  });
  const currentItem = JSON.parse(
    JSON.stringify(
      currentItemDb.get({
        raw: true
      })
    )
  );
User.upsert(
      { ...currentItem, ...data },
      {
        where: {
          id: {
            [Op.eq]: data.id
          }
        },
        include: [Address]
      }
    )
const currentItemDb = await User.get(securityObj, id);
await currentItemDb.update(data);
await sequelize.transaction({}, async t =>
   const currentItemDb = await User.get(securityObj, id);
   await currentItemDb.update(data, { transaction: t});
   await Address.destroy({
       where: {
           userId: {
                 [Op.eq]: id
           }
       },
       transaction: t
   });
   // Not sure how to create with automatically inserted createdAt and updatedAt here.
   data.addresses.forEach(async address => {
      address.userId = id;
      await Address.create(address);
   }, {
         transaction: t
   });
});

What do you expect to happen?

I would expect Sequelize to figure out which records were added, updated and deleted and execute the appropriate sql. Barring that (I saw that some of this functionality is part of open issues), I would like to know the most elegant way to achieve this and I would expect these kinds of CRUD operations to be well documented. This is the ABCs of Sequelize after all and documentation is very light or non existent in key areas like this.

What is actually happening?

update doesn't update associations.
There is no documentation on the best way to do this.

Dialect: mysql
Database version: 5.7.x
Sequelize version: 4.37.10
Tested with latest release: Yes

Activity

  1. Wsiegenthaler commented on Aug 19, 2018

    @Wsiegenthaler
    Contributor
  2. nyenye commented on Oct 4, 2018

    @nyenye

    Right now SO is on maintenance, but I think it's this post which has an answer from a developer explaining the best way to update attributes from an associated model.

    Bad thing, it's from 2014, so I don't know how well it stands today.

    I join to this issue. Could someone make an example on how to best update associated models values? Also with different types of relationships (1:1, 1:m, m:n) if it's possible at all.

    Right now the only thing that comes to mind is something like the following, for a 1:m relationship:

    Model.hasMany(AssociatedModel)
    AssociatedModel.belongsTo(Model)
    AssociatedModel.update(updateData, {where: modelInstance.id})
  3. stale commented on Jan 10, 2019

    @stale
  4. papb commented on Jan 16, 2020

    @papb
    Member

    This has been centralized in #11836

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions