javascript - Bookshelfjs where clause on join -
i started using bookshelfjs, , couldn't find clear answer on how following.
consider have following tables:
product -------- id product_account -------- id product_id account_id collection -------- id collection_product_account -------- collection_id product_account_id
there can many products collection.
i want following
select pa.*, p.* product_account pa inner join collection_product_account cp on cp.product_account_id = pa.id inner join product p on p.product_account_id = pa.product_id cp.collection_id = ?
how able pass in collection id, , return whole list of product_accounts, , products that?
for reference, doing if querying product_account_id
new productaccountmodel() .where({account_id: 1}) .fetchall({withrelated: ['product']}) .then(function(productaccounts) { return productaccounts.tojson()); });
i'm assuming model:
var product = bookshelf.model.extend({ tablename: 'product', collections: function() { return this.belongstomany(collection); } }); var collection = bookshelf.model.extend({ tablename: 'collection', products: function() { return this.belongstomany(product); } });
then have switch logic bit. once new product()
, can't query related table. can switch it, this:
new collection({id: 1}).fetch({ withrelated: ['products'] }).then(function(result) { res.json(result.tojson()); });
does help?
update:
if necessary, can additionally attach relations model attaching, i.e.:
new collection({id: 1}).fetch({ withrelated: ['products.company'] }).then(function(result) { res.json(result.tojson()); });
Comments
Post a Comment