续集 hasMany、belongsTo 或两者兼而有之? [英] Sequelize hasMany, belongsTo, or both?

查看:12
本文介绍了续集 hasMany、belongsTo 或两者兼而有之?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想正确设置与 sequelize 的一对一或一对多关系,事实上,如果我使用 hasOne 中的任何一个,这一切似乎都可以正常工作/hasManybelongsTo 在我的模型定义中.例如,以下关联确实会在其目标上创建 userId 字段:

I want to properly setup one-to-one or one-to-many relationship with sequelize and as a matter of fact it all seems to be working just fine if i use either one of hasOne/ hasMany or belongsTo in my model definition. For example the following associations do create the userId field on their Targets:

    User.hasMany(Email, {
        as: 'emails',
        foreignKey: 'userId',
    })

    User.hasOne(Profile, {
        as: 'profile',
        foreignKey: 'userId',
    })

但我几乎在官方文档中的所有地方都看到了类似的内容:

But almost everywhere in official docs i see something like:

   Projects.hasMany(Tasks);
   Tasks.belongsTo(Projects);

hasManybelongsTo 一起使用.

这真的是必需的还是只使用其中一个就足够了?任何进一步的解释都将非常有价值.谢谢!

Is this really required or it is enough to use just one of them? Any further explanation would be really valuable. Thanks!

推荐答案

使用 belongsTo 定义关联模型的所有权.为了更详细地解释这一点,我将参考教程中引用的示例

Using belongsTo defines the ownership of the associated models. To explain this in more detail I will refer to the example cited from the tutorials

Project.hasMany(Task);
Task.belongsTo(Project);

假设您不再对已删除项目的任务感兴趣.在这种情况下,如果您没有定义 belongsTo 关联,您将不得不手动删除任务.belongsTo 建立项目对其任务的所有权,数据库也会自动删除属于已删除项目的任务.这称为级联删除,可以链接多个表.

Assume that you are no longer interested in the tasks of a deleted project. In that case you would have to delete the tasks manually, had you not defined the belongsTo association. belongsTo establishes an ownership of projects over it's tasks and the database will automatically delete the tasks belonging to the deleted project as well. This is called cascading delete and can chain over multiple tables.

如果你运行下面的代码片段

If you run the following code snippet

const Project = sequelize.define('project', {
    name: Sequelize.STRING
});
const Task =  sequelize.define('task', {
    name: Sequelize.STRING
});
Project.hasMany(Task);
Task.belongsTo(Project);

在 sequelize 脚本中并观察输出

in a sequelize script and watch the output

Executing (default): DROP TABLE IF EXISTS `projects`;
Executing (default): CREATE TABLE IF NOT EXISTS `projects` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL);
Executing (default): PRAGMA INDEX_LIST(`projects`)
Executing (default): DROP TABLE IF EXISTS `tasks`;
Executing (default): CREATE TABLE IF NOT EXISTS `tasks` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` VARCHAR(255), `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, `projectId` INTEGER REFERENCES `projects` (`id`) ON DELETE SET NULL ON UPDATE CASCADE);

您会注意到在创建任务表时设置的级联行为.

you will notice the cascading behaviour being set in the creation of the tasks table.

说了这么多,最后的答案是:视情况而定.belongsTo 的使用可能会非常方便,如果您宁愿保留已删除项目的任务,那么这将是致命的.仅当 belongsTo 在您的应用程序上下文中有意义时才使用.

So much said, the final answer is: it depends. The use of belongsTo can come very handy or will be fatal if you would rather keep the tasks of the deleted project. Only use belongsTo if it makes sense in the context of your application.

这篇关于续集 hasMany、belongsTo 或两者兼而有之?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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