如何在Node.js和Sequelize中从连接表中查询数据?

huangapple go评论82阅读模式
英文:

How to query from from joined table in Node.js and Sequlieze?

问题

我有两个主要的表格,Book(属性:name,author)和Collection(属性:collection_name),还有一个通过Book.BelongsToMany(Collection)和Collection.BelongsMany(Book)关联它们的表格。

现在我想通过搜索name、author或collection_name来查找书籍。

以下是我的查询代码:

router.get("/search", (req, res) => {
  const { term } = req.query;
  console.log(term)
  Book.findAll({
    include: [
      {
        model: Collection,
       
      },
    ],
    where: { 
      [Op.or]:[
      {name: { [Op.like]: "%" + term + "%" }},
      {author: { [Op.like]: "%" + term + "%"}}
      ]
    }
  }).then((book) => {
      res.status(200).json(book);
    })
    .catch((err) => res.status(404).json({ error: err }));
});

当我搜索name或author时,这个查询给我显示了正确的结果。但是如何在这个查询中搜索collection_name呢?请帮帮我。

英文:

I have to main table Book (atrributes: name, author) and Collection(atrribute: collection_name)and a table that joins them with Book.BelongsToMany(Collection) and Collection.BelongsMany(Book) association

Now I want to find the books by searching for name, author or collection_name

here is my query

router.get("/search", (req, res) => {
  const { term } = req.query;
  console.log(term)
  Book.findAll({
    include: [
      {
        model: Collection,
       
      },
    ],
    where: { 
      [Op.or]:[
      {name: { [Op.like]: "%" + term + "%" }},
      {author: { [Op.like]: "%" + term + "%"}}
      ]
    }
  }).then((book) => {
      res.status(200).json(book);
    })
    .catch((err) => res.status(404).json({ error: err }));
});

This query shows me correct results when I searched for name or author . But how to search for collection_name in this query? Plaese help me out

答案1

得分: 0

在使用include进行连接时,为Collection添加一个别名,并在collection_name列上进行查询。美元符号($)用作占位符,用于引用关联模型的列。
您还可以直接使用模型名称与$。

Book.findAll({
    include: [
      {
        model: Collection,
        as: 'collection'
      },
    ],
    where: { 
      [Op.or]:[
      {name: { [Op.like]: "%" + term + "%" }},
      {author: { [Op.like]: "%" + term + "%"}},
      {'$collection.collection_name$': { [Op.like]: "%" + term + "%"}}}
      ]
    }
)
英文:

Add an alias name for Collection while joining using include and then query on the collection_name column. The dollar symbol ($) is used as a placeholder to reference columns from associated models.
You can also directly use model name with $.

Book.findAll({
    include: [
      {
        model: Collection,
        as: 'collection'
      },
    ],
    where: { 
      [Op.or]:[
      {name: { [Op.like]: "%" + term + "%" }},
      {author: { [Op.like]: "%" + term + "%"}},
      {'$collection.collection_name$': { [Op.like]: "%" + term + "%"}}}
      ]
    }
)

huangapple
  • 本文由 发表于 2023年8月9日 12:36:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864616.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定