user6467981
user6467981

Reputation:

Adding associations to sequelizejs models

I have defined a model (by using sequelize-cli) as such:

'use strict';
module.exports = function(sequelize, DataTypes) {
var Rating = sequelize.define('Rating', {
  star_count: DataTypes.FLOAT,
  details: DataTypes.TEXT
}, {
  classMethods: {
    associate: function(models) {
      Rating.hasOne(models.Product);
  }
 }
});
return Rating;
};

However when I query Rating in the database after I db:migrate I get:

SELECT * from "Ratings";
 id | star_count | details | createdAt | updatedAt
----+------------+---------+-----------+-----------

The documentation really doesn't say anything different than what I did above. I'd expect to see a product_id field in here. What am I doing wrong?

EDIT:

Sequelize-CLI creates a file called index.js in models. It looks like this:

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config.js')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  var sequelize = new Sequelize(config.database, config.username,     config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== basename) &&     (file.slice(-3) === '.js');
  })
  .forEach(function(file) {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
 });

Object.keys(db).forEach(function(modelName) {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
 });

 db.sequelize = sequelize;
 db.Sequelize = Sequelize;

 module.exports = db;

This appears to be calling the associate method, which calls the the appropriate functions (hasMany, etc) and according to the documentation should set up the right relationships. This tutorial seems to corroborate this logic.

Upvotes: 1

Views: 1432

Answers (1)

Keval
Keval

Reputation: 3326

Sequelize migration will create changes according to migration file so you need to specify the foreign key with reference as shown here https://stackoverflow.com/a/23035179/4583460

The Sequelize.sync command will create any aditional keys required for the association. So either use sync or mention change your migration file to include foreign key ref.

Upvotes: 2

Related Questions