I'm trying to use Sequelize with legacy table and stuck how to define one-to-many connection of my database in Sequelize`s model.
I have the following tables:
pesons:
+----+---------+-------------+
| id | name | language_id |
+----+---------+-------------+
| 1 | Anatoly | 1 |
| 2 | Roman | 2 |
| 3 | Pavel | 1 |
+----+---------+-------------+
and
languages:
+----+---------+
| id | value |
+----+---------+
| 1 | English |
| 2 | Hebrew |
| 3 | Russian |
+----+---------+
Like you can see, every Person
can know one Language
but same Language
can be known by different Persons
.
var Person = sequelize.define('person', {
id : {
field: 'id',
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name : {
field: 'name',
type: Sequelize.TEXT
}
},{
tableName: 'persons',
timestamps: false
});
var Language = sequelize.define('language', {
id : {
field: 'id',
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
value : {
field: 'value',
type: Sequelize.TEXT
}
},{
tableName: 'languages',
timestamps: false
})
According to official manual: Difference between HasOne and BelongsTo
When information about association is present in source model we can use belongsTo.
I need to define relations between Person
and Language
as:
Person.belongsTo(Language);
But it looks wrong to me and counter intuitive, so I'd like to get some clarification from somebody.
P.S. For the sake of clarity, I've never used any ORM before.
In usual case it would be every Person can know many Language but same Language can be known by different Persons
so there is many to many association so we do many to many association http://docs.sequelizejs.com/en/latest/docs/associations/#nm
But for your use case kindly rephrase your scentence as
Languages has many persons (users), So here comes one to many association, there is no part of has one association.
belongs to and has many must be used in pairs, since they are counter parts
So first
Language.hasMany(Person)
The orm will add all the essential instance and class method to languages so that you can easily query, add and delete a person to a language.
Second part
Person.belongsTo(Language)
The orm will add all the essential instance and class method to Persons so that you can easily query, add and delete a Language to a person.