Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

node.js - Sequelize model references vs associations

Just starting to use Sequelize and I've setup a bunch of models and seeds, but I can't figure out references vs associations. I don't see the use case for references if they even do what I think they do, but I couldn't find a good explanation in the docs.

Is this redundant having references and associations?

module.exports = (sequelize, DataTypes) => {
  const UserTask = sequelize.define('UserTask',
    {
      id: {
        primaryKey: true,
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4
      },
      userId: {
        type: DataTypes.UUID,
        references: { // <--- is this redundant to associate
          model: 'User',
          key: 'id'
        }
      }
      // ... removed for brevity
    },
    {
      classMethods: {
        associate: models => { <--- makes references redundant?
          UserTask.belongsTo(models.User, {
            onDelete: 'CASCADE',
            foreignKey: {
              fieldName: 'userId',
              allowNull: true,
              require: true
            },
            targetKey: 'id'
          });
        }
      }
    }
  );
  return UserTask;
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using references you create a reference to another table, without adding any constraints, or associations. Which means that is just a way of signaling the database that this table has a reference to another.

Creating an association will add a foreign key constraint to the attributes. And the you can perform all the magic behind it the association functions. i.e User.getTasks();

More info about references here: https://sequelize.readthedocs.io/en/latest/docs/associations/#foreign-keys_1

About association here: http://docs.sequelizejs.com/manual/tutorial/associations.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...