续集模型参考与关联 [英] Sequelize model references vs associations

查看:12
本文介绍了续集模型参考与关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始使用 Sequelize,我已经设置了一堆模型和种子,但我无法弄清楚引用与关联.如果他们甚至按照我的想法去做,我看不到参考的用例,但我在文档中找不到很好的解释.

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;
};

推荐答案

使用 references 您可以创建对另一个表的引用,而无需添加任何约束或关联.这意味着这只是向数据库通知此表引用另一个数据库的一种方式.

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.

创建 association 将为属性添加外键约束.您可以执行关联功能背后的所有魔法.即 User.getTasks();

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();

有关 references 的更多信息:https://sequelize.readthedocs.io/en/latest/docs/associations/#foreign-keys_1

关于 association 此处:http://docs.sequelizejs.com/manual/tutorial/associations.html

这篇关于续集模型参考与关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆