续集hasMany,belongsTo或两者皆有? [英] Sequelize hasMany, belongsTo, or both?

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

问题描述

我想通过续集正确设置一对一或一对多关系,事实上,如果我使用 hasOne / hasMany belongsTo 在我的模型定义中。
例如,以下关联确实在其目标上创建了 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);

有很多 belongsTo 一起使用。

是这真的是必需的,还是仅使用其中之一就足够了?任何进一步的解释都是非常有价值的。谢谢!

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.

如果运行以下代码段

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

在一个序列化脚本中,观察输出

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天全站免登陆