node.js - Sequelize.js - how to properly use get methods from associations (no sql query on each call)? -
i'm using sequelize.js orm , have few associations (which doesn't matter now). models get
, set
methods associations. (from docs):
var user = sequelize.define('user', {/* ... */}) var project = sequelize.define('project', {/* ... */}) // one-way associations project.hasone(user) /* ... furthermore, project.prototype gain methods getuser , setuser according first parameter passed define. */
so now, have project.getuser()
, returns promise. if call twice on same object, sql query executed twice.
my question - missing out, or expected behavior? don't want make additional queries each time call same method on object.
if expected - should use custom getters member variables manually populate , return if present? or there more clever? :)
update debugger's answer - understand can use includes
when making query in order eager load everything, don't need it, , can't time. it's waste of resources , big overhead if load entire db @ beginning, understand (by criteria) won't need it. want make additional queries depending on situation. can't afford destroy models (dao objects) have , create new ones, info inside them. should able update parts of them, missing (from relations).
if use getuser() make query call, dosent give access user. can manually save project.user or project.users depending on association.
but can try eager loading
project.find({ include: [ { model: user, as: 'user' } // here have specify same alias did in association ] }).success(function(project){ project.user // contains user });
also e.g of getuser(). dont expect automatically cache user , dont override cleverly create side effects. getuser expected database , should!
project.getuser().then(function(user){ // user available , sequelize object project.user = user; // save project.user , use till u want })
Comments
Post a Comment