Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize.js foreign key

When using Sequelize.js, the following code doesn't add any foreign key on tables.

var MainDashboard = sequelize.define('main_dashboard', {   title: Sequelize.STRING }, {   freezeTableName: true })  MainClient.hasOne(MainDashboard, { foreignKey: 'idClient' }) MainDashboard.hasOne(MainClient, { foreignKey: 'clientId' })  sequelize.sync({ force: true }) 

Is there any way to force Sequelize.js to add these foreign key constraints?

like image 885
swampcypress Avatar asked Jan 05 '13 07:01

swampcypress


People also ask

What is Sequelize target key?

The target key is the column on the target model that the foreign key column on the source model points to.

How do I create a composite key in Sequelize?

You can create composite primary keys in Sequelize by specifying primaryKey: true against more than one column. E.g. how can we associate a table to this composite key.

What is a foreign key column?

A foreign key is a column (or combination of columns) in a table whose values must match values of a column in some other table. FOREIGN KEY constraints enforce referential integrity, which essentially says that if column value A refers to column value B, then column value B must exist.


2 Answers

Before I had the same problem, and solved when I understood the functioning of settings Sequelize.

Straight to the point!

Suppose we have two objects: Person and Father

var Person = sequelize.define('Person', {          name: Sequelize.STRING });  var Father = sequelize.define('Father', {          age: Sequelize.STRING,         //The magic start here         personId: {               type: Sequelize.INTEGER,               references: 'persons', // <<< Note, its table's name, not object name               referencesKey: 'id' // <<< Note, its a column name         } });  Person.hasMany(Father); // Set one to many relationship 

Maybe it helps you

Edit:

You can read this to understand better:

http://docs.sequelizejs.com/manual/tutorial/associations.html#foreign-keys

like image 142
Ilsondotcom Avatar answered Sep 19 '22 04:09

Ilsondotcom


For Sequelize 4 this has been updated to the following:

 const Father = sequelize.define('Father', {         name: Sequelize.STRING });  const Child = sequelize.define('Child', {     age: Sequelize.STRING,     fatherId: {        type: Sequelize.INTEGER,        references: {           model: 'fathers', // 'fathers' refers to table name           key: 'id', // 'id' refers to column name in fathers table        }     } });  Father.hasMany(Child); // Set one to many relationship  

Edit: You can read more on associations at https://sequelize.org/master/manual/assocs.html

like image 33
codejockie Avatar answered Sep 21 '22 04:09

codejockie