Bookshelf.js accessing multiple tables that are related -
i'm dealing 3 tables.
right can feed of user (activities table) , activitytypes object (id,type activitytypes table), need related_user (users table) object of given activity, i'll know details of related_user if column isn't empty.
users
id email username password_hash activitytypes
id type activities
id user_id (foreign key users, owner of activity) status activitytype_id (foreign key activitytypes) related_user (foreign key users. shows relation user_id, if there's any. if activitytype_id 2 or 3, shown "followed, "commented", etc.) my models
var activitytype = db.model.extend({ tablename: 'activitytypes', hastimestamps: false }); var activity = db.model.extend({ tablename: 'activities', hastimestamps: true, activitytypes: function() { return this.belongsto(activitytype); } }); var user = db.model.extend({ tablename: 'users', hastimestamps: true, feed: function() { return this.hasmany(activity); } }); this existing query, how can add related_user object it?
user.where({id : 43}).fetchall({withrelated : ['feed.activitytypes']}).then(function(data) { data = data.tojson(); res.send(data); });
i solved it.
i added new method activity, below.
userrelated : function() { return this.belongsto(user,'related_user'); } and here's updated query. don't know whether it's right way or not in terms of optimization, works.
user.where({ id: 43 }).fetchall({ withrelated: ['feed.userrelated', 'feed.activitytypes'] }).then(function(data) { data = data.tojson(); res.send(data); }); right feed, userrelated , activitytypes return without problem, in data in json format.
Comments
Post a Comment