Bookshelfjs where 连接子句
Bookshelfjs where clause on join
我刚开始使用 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,以及 return 整个 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()
,你就不能通过相关的table来查询这个了。但你可以切换它,像这样:
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());
});
我刚开始使用 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,以及 return 整个 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()
,你就不能通过相关的table来查询这个了。但你可以切换它,像这样:
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());
});