Reputation: 614
I am creating a self referencing hasMany relation using this simple piece of code:
Story.hasMany(models.Story, {
as: {singular: 'parent', plural: 'children'},
foreignKey: 'fk_parent'
});
As you can see, the story entity can have multiple story entity children. Using that piece of code I would expect sequelize to create two functions on each story model instance:
story.getParent();
story.getChildren();
But it doesn't.
hasMany is definitely called, because my table does contain the fk.
Let's assume I have a story with id = 1 and fk_parent = 2. As far as I understand getChildren() should return all stories with fk_parent = 1 and getParent() should return the story with the id = 2. Am I correct or do I get something substantially wrong?
What am I doing wrong?
My complete model is:
class Story extends Model {
static tableName = 'Story';
static associate(models) {
Story.hasMany(models.Story, {
as: {singular: 'parent', plural: 'children'},
foreignKey: 'fk_parent'
});
Story.hasMany(models.Story, {
as: {singular: 'original', plural: 'reprints'},
foreignKey: 'fk_reprint'
});
Story.belongsTo(models.Issue, {foreignKey: 'fk_issue'});
Story.belongsToMany(models.Individual, {through: models.Story_Individual, foreignKey: 'fk_story', unique: false});
Story.belongsToMany(models.Appearance, {through: models.Story_Appearance, foreignKey: 'fk_story'});
}
export default (sequelize) => {
Story.init({
id: {
type: Sequelize.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
title: {
type: Sequelize.STRING(255),
allowNull: false,
default: ''
},
number: {
type: Sequelize.INTEGER,
allowNull: false,
},
pages: {
type: Sequelize.STRING(255),
allowNull: false
},
addinfo: {
type: Sequelize.STRING(255),
allowNull: false,
defaultValue: ''
}
}, {
indexes: [{
unique: true,
fields: ['fk_issue', 'fk_parent', 'addinfo', 'number']
}],
sequelize,
tableName: Story.tableName
});
return Story;
};
Upvotes: 0
Views: 716
Reputation: 614
I forgot the Story.belongsTo(models.Story, { as: 'parent', foreignKey: 'fk_parent' });
. Thanks to Anatoly!
Upvotes: 1