How sequelize works?

前端 未结 3 1850
时光取名叫无心
时光取名叫无心 2021-01-23 01:26

I\'m trying to understand how sequelize works on a simple example : User can have many posts and post can have only one user.

First question, I don\'t know if I have to

3条回答
  •  不思量自难忘°
    2021-01-23 02:11

    You are right you have to manually set the foreign key relations.

    Here is official documentation link : http://docs.sequelizejs.com/manual/tutorial/associations.html

    You can try following code:

    var user_object = require('your_file_path');
    var post_object = require('your_file_path');
    
    user_object.hasMany(post_object, {
        foreignKey: 'user_id',
        sourceKey: 'user_id',
        onDelete: 'cascade',
        as:'Posts',
    });
    
    post_object.belongsTo(user_object, {
        foreignKey: 'user_id',
        sourceKey: 'user_id',
        onDelete: 'cascade',
        as:'Posts',
    });
    

提交回复
热议问题