Javascript 关于join的bookshelfjswhere子句
我刚开始使用BookshelfFJS,但我找不到关于如何执行以下操作的明确答案 假设我有以下表格:Javascript 关于join的bookshelfjswhere子句,javascript,bookshelf.js,knex.js,Javascript,Bookshelf.js,Knex.js,我刚开始使用BookshelfFJS,但我找不到关于如何执行以下操作的明确答案 假设我有以下表格: product -------- id product_account -------- id product_id account_id collection -------- id collection_product_account -------- collection_id product_account_id 一个集合可以有许多产品 我想做以下几件事 SELECT pa.
product
--------
id
product_account
--------
id
product_id
account_id
collection
--------
id
collection_product_account
--------
collection_id
product_account_id
一个集合可以有许多产品
我想做以下几件事
SELECT pa.*, p.* FROM 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
WHERE cp.collection_id = ?
我如何才能传入一个集合id,并返回整个product_帐户列表,然后从中获取产品
作为参考,如果我使用产品\帐户\ id进行查询,我会这样做
new productAccountModel()
.where({account_id: 1})
.fetchAll({withRelated: ['product']})
.then(function(productAccounts)
{
return productAccounts.toJSON());
});
我假设这是你的模型:
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);
}
});
然后你必须稍微转换一下逻辑。一旦你说了newproduct()
,你就不能通过相关的表来查询了。但你可以这样切换:
new Collection({id: 1}).fetch({
withRelated: ['products']
}).then(function(result) {
res.json(result.toJSON());
});
这有用吗
更新:
如有必要,还可以附加所附加模型中的关系,即:
new Collection({id: 1}).fetch({
withRelated: ['products.company']
}).then(function(result) {
res.json(result.toJSON());
});
现在返回一个集合“collection”。我如何使它返回“产品”?实际上,我有更多相关的附加到“产品”,我想附加在它旁边。现在更新问题以反映这一点。是的,这将返回具有所需Id的单个集合,但您已将属于该集合的所有产品附加到响应。如果您想加载更多与产品相关的内容,可以将其添加到withRelated中,例如,'product.type'Ah,
withRelated:[productAccount],[productAccount.product]
让我更接近。我想这可能是我能做的最好的了?希望它能在productAccount中返回一级。但是,我会在事实发生后再处理。谢谢作为对结果答案的补充:result.map(函数(集合){return collection.toJSON().productAccount;})