jmls
jmls

Reputation: 2969

sequelize associations

I'm trying to use sequelizejs 1.4, and after reading the docs, am still confused about associations.

var User = sequelize.define('User', {/* ... /}) var Project = sequelize.define('Project', {/ ... */})

Project.hasOne(User)

do I have to include this code every time ? I was trying to separate out the models to single files, but looking at this makes me think that I need to have user defined in the project model.

Or, do I need to associate the models at a higher level ?

p1 = new Project() u1 = new User()

p1.hasOne(u1)

just doesn't seem right to me. I know that I must be missing something obvious, and just need someone to pull the switch that turns on the light :)

Thanks

Upvotes: 1

Views: 2121

Answers (2)

Totty.js
Totty.js

Reputation: 15861

For each model create a file like this: Car.js, City.js

Then in each model you do like this:

module.exports.getModel = function(sequelize){sequelize.define("Car"...)}
module.exports.setAssociations(models){models.Car.hasOne(models.City)}

To do this you want to abstract away the way is done like this:

        var sequelize = this.__connection;
        var Sequelize = require('sequelize');
        var rootFolder = this.__rootFolder;
        var modelsNames = this.getModelsNames(rootFolder);

        var i = k = modelsNames.length;
        var modelName;
        var models = {};
        var modelFactoryFn;

        // load models
        while(i--){
            modelName = modelsNames[i];
            var Model = require(path.resolve(rootFolder, modelName)).getModel(sequelize);
            if(!Model){
                throw new Error("No model returned from " + path.resolve(rootFolder, modelName));
            }
            models[modelName] = Model;
        }

        // build associations
        var modelFile;

        while(k--){
            modelName = modelsNames[k];
            modelFile = require(path.resolve(rootFolder, modelName));
            if(modelFile.buildAssociations){
                modelFile.buildAssociations(models);
            }
        }

        this.__models = models;

I know it can be better but this allows you to work right now, and is better explained than with words.

Upvotes: 0

leeway
leeway

Reputation: 484

Short answer, yes.

Just create an association file that will have the associations:

module.exports = function(db){
var sup = db.import(__dirname+'/sup.js');
var node = db.import(__dirname+'/node.js');

sup.hasMany(node);
node.hasOne(sup);
return db;
}

Now in your app or main file just require this after you create your database:

var database = new Sequelize(...);
database = require(__dirname+'/association.js');
database.sync();

Upvotes: 3

Related Questions