Sequelize-连接varchar和varchar数组

时间:2018-11-15 15:30:11

标签: sequelize.js

我正在尝试将以下PostgreSQL查询转换为Sequelize:

select reviews.product_id, products.brand
  from reviews inner join products 
  on reviews.product_id = any(products.product_id);

reviews.product_id是一个varchar,而products.product_id是一个varchar数组,这就是为什么我使用any运算符的原因。我创建了此Sequelize查询以尝试复制上面的查询,但是它只返回一个空对象。

db.reviews.findAll({
  attributes: ["product_id"],
  include: [{
    model: db.products,
    as: "products",
    on: {
      col1: where(col("reviews.product_id"), "=", {[Op.contains]: [col("products.product_id")]})
    },
    required: true,
    attributes: ["brand"]
  }],
  limit: 10
})
  .then(reviews => res.json(reviews))
  .catch(err => res.json(err));

PostgreSQL查询按预期方式工作,所以我知道它应该返回一些东西。对于上下文,我在我的reviews模型中设置了以下belongsTo关联:

myModel.associate = models => {
  myModel.belongsTo(models.products, {foreignKey: "product_id", targetKey: "product_id", as: "products"});
};

我不知道如何准确地指定我要加入不同的类型(varchar和varchar数组)以获得所需的结果。有人知道解决方案吗?

1 个答案:

答案 0 :(得分:0)

只是想通了。我使用了错误的运算符。我刚刚将export interface ListContactsQuery_contacts_edges { __typename: "ContactEdge"; /** * The item at the end of the edge. */ node: ListContactsQuery_contacts_edges_node | null; } export interface ListContactsQuery_contacts { __typename: "ContactConnection"; /** * A list of edges. */ edges: (ListContactsQuery_contacts_edges | null)[] | null; } export interface ListContactsQuery { /** * Gets all contacts for the current user */ contacts: ListContactsQuery_contacts; } 中的on自变量更改为:

include

收件人:

on: {
  col1: where(col("reviews.product_id"), "=", {[Op.contains]: [col("products.product_id")]})
}