我刚开始使用 bookshelfJS,我找不到关于如何执行以下操作的明确答案。
考虑我有以下表格:
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_accounts 列表,然后从中获取产品?
作为引用,如果我使用 product_account_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);
}
});
然后你必须稍微切换一下逻辑。一旦你说 new Product()
,你就不能通过相关表查询它。但是您可以像这样切换它:
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());
});
关于javascript - Bookshelfjs where 连接子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29874599/