Associations of Model
Does it generate associations of all foreign / primary keys as well from the tables definition?
I just ran this on my database and found that it doesn't use the FKs to make any associations.
However, it should. The foreign keys with existing data-set is the whole problem in my case as well.
dont know how hard it is to do,but this feature missing will drop all users/developers
I just found the project and if it is possible I`ll use it. So did anyone manage to get associations working?
Hello, Do you have new about this? It would be nice that relations will be created automatically
No, sorry.
Somebody want to help me to improve this repo adding association skills?
Relations should be added now... please let me know if you run into any problems @Yamilquery @stefanikolov @diegomesata
Closing this issue.. if there are problems please open a new ticket.
Facing issues with this. The associations are visible in the generated files eg: .... myExternalId : { type : DataTypes.INT, reference : { model : "myExternal", id : "id" } }
However when called it tells me that there is no association with the "myExternal' model. And after searching through sequelize there is no way of associating tables like this. I can provide real snap of code.
Same problema as @omomthings here
@weldermarcosxd I have found the solution since then. You should not do it that exact way, instead use an association method, cant find the link where I found it so here is an exemple:
In each model file generated by sequelize auto you add an 'associate' method, you'll have something like this :
MyModel.js
module.exports = function (sequelize, DataTypes) {
var Interests = sequelize.define('Interests', {
idInterest: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true,
field:'id_interest'
},
.......
}, {
classMethods: {
associate: function (models) {
// here in the models object you have all the defined models, and can associate each of them like you would manualy do
}
}
});
return Interests;
};
You will then have a centralize module that 1 - loads all models 2 - associate them (by calling the associate methode above)
you'll have something like this, note that you should have all your models and following file in the same directory and nothing else, as we read all the files (it's more generic and better):
index.js
var fs = require('fs'),
path = require('path'),
Sequelize = require('sequelize'),
config = require('../../config/config'),
db = {};
var sequelize = new Sequelize(config.db.database,config.db.username,config.db.password,config.db.config);
//read each file in the same repo, we considere all files as models
fs.readdirSync(__dirname).filter(function (file) {
return (file.indexOf('.') !== 0) && (file !== 'index.js');
}).forEach(function (file) {
//initialize each and add it the our models holder
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
//call associate on each class and create the associations
Object.keys(db).forEach(function (modelName) {
db[modelName].schema = 'sork_developmentqsdf';
if ('associate' in db[modelName]) {
db[modelName].associate(db);
}
});
//note that you still need to call sequelize.sync() in order to the db to be usable
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
there you go, you'll just need to import the index.js and you'll have all your classes
Thanks dude, but still no luck.
module.exports = function (sequelize, DataTypes) {
return sequelize.define('cliente', {
id: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
...
}, {
tableName: 'cliente',
timestamps: false,
classMethods: {
associate: function (models) {
models['cliente'].hasMany(models['pedido'], {
foreignKey: 'cliente',
targetKey: 'id'
});
}
}
});
};
the other side
/* jshint indent: 1 */
module.exports = function (sequelize, DataTypes) {
return sequelize.define('pedido', {
id: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
...
}, {
tableName: 'pedido',
timestamps: false,
classMethods: {
associate: function (models) {
models['pedido'].belongsTo(models['cliente'], {
as: 'clientes'
});
}
}
});
};
The assossiate method is called but still I got :
Error: cliente is not associated to pedido!
when I query:
models.rotas.findAll({
attributes: ['id', 'descricao'],
include: [{
model: models['pedido'],
attributes: [
'id', 'numero_pedido'
],
include: [{
model: models['cliente'],
attributes: [
'id', 'razao_social', 'endereco'
]
}]
}],
where: {
id: 1889
}
}
Does anyone have any ideas? Im quite new to sequelize and this joining thing is quite hard to understand.
You should try to keep it simple first till you find where is the problem coming from, because the code I sent you is working for me. Did you call sequelize.sync({force:true}) (this will drop all the DB, watch out for data loss) ? Cause if the DB already exist the associations won't be created.. next after loading the DB, go check through PHPmyadmin (or whatever) if the associations are there. It is likely to be a simple problem with the 'as' attribute you use.. try step by step to find out where the problem is coming from, but it's the right way
Thank you once more. The sequelize.sync is something new to me and yes, my database already exists I bet thats the problem all along. I've been using sequelize-auto for generating the models from the database but seems lika a bad idea now as long I can't work with relations.
No it's a good idea, however that's what I used, it's just that when you use this technique, you have to use sequelize.sync({force:true}). sequelize.sync() creates the tables (but only if it don't exist) and it doesn't modify them. If you need to modify the tables, you must specify it (with sequelize.sync( { force:true } ) ) this will drop the tables if they exist before recreating them, therefor the data will be lost, but if you don't have any data for now, you can use it with no harm. Good luck.