javascript - Bookshelfjs where 连接子句

标签 javascript bookshelf.js knex.js

我刚开始使用 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/

相关文章:

javascript - Grunt - grunt-eslint 不启动任务

javascript - 如何转换为使用 Promises 和 Q Library

javascript - 单击外部以关闭下拉头像菜单

bookshelf.js - 使用 UpdatePivot 附加 "Not Null"列

javascript - Node.js 数据表编辑器 - 多列的自定义/唯一验证

mysql - 具有唯一约束功能的 Knex.js 迁移

javascript - Jquery 检测 JQuery 更新时的变化

node.js - 使用 Bookshelf.js 在数据透视模型上设置时间戳

express - knex.js - 仅调试 SQL

postgresql - Strapi:初始化/填充数据库