Sequelize hasMany, belongsTo, or both?

后端 未结 1 816
不思量自难忘°
不思量自难忘° 2021-02-15 02:02

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

相关标签:
1条回答
  • 2021-02-15 02:36

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

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题