【问题标题】:Use of where in sequelize在 sequelize 中使用 where
【发布时间】:2022-01-19 14:43:08
【问题描述】:

我正在使用以下关于 sequelize 的数据:

{
  name: "Matti Luukkainen",
  username: "mluukkai@iki.fi",
  wish_read: [
    {
      id: 3,
      url: "https://google.com",
      title: "Clean React",
      author: "Dan Abramov",
      likes: 34,
      year: null,
      reading_lists: [
        {
          read: true,
          id: 2
        }
      ]
    },
    {
      id: 4,
      url: "https://google.com",
      title: "Clean Code",
      author: "Bob Martin",
      likes: 5,
      year: null,
      reading_lists: [
        {
          read: false,
          id: 2
        }
      ]
    }
  ]
}

我想使用命令where 过滤数据,只显示reading_lists.read = true 所在的博客。我的实现是下面的代码,但是过滤器不起作用。我想我不能直接在where 中传递一个对象,但我想不出另一种方式来做到这一点。

const user = await User.findByPk(req.params.id,{
    attributes: { exclude: ['id', 'createdAt', 'updatedAt']},
    include: [
        { 
        model: Blog, 
        as: 'wish_read',
        attributes: { exclude: ['userId']},
        through: {
            attributes: { exclude: ['user_id', 'blog_id', 'blogId', 'userId'] }
        },
        attributes: { exclude: ['id', 'createdAt', 'userId', 'updatedAt'] }

        },
    ],
    where: {
        wish_read.reading_lists.read: true
    }
})

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    你需要像这样用$ 包裹一个列路径:

     where: {
            '$wish_read.reading_lists.read$': true
        }
    

    【讨论】:

      【解决方案2】:

      您正在使用 findByPk(通过私钥查找)。当您已经拥有 ID 并且只想加载一个对象时,您可以使用该函数。您应该使用 findOne 来处理过滤器。另外,如果reading_list也是一个实体,可以嵌套include参数,里面使用where参数。

      例如:

      包括:[ { 型号:博客, 如:'wish_read', 包括: [ { 型号:阅读列表, 如:'reading_lists', 其中:{读:真} } ] } ]

      【讨论】:

        猜你喜欢
        • 2020-03-25
        • 2018-07-10
        • 1970-01-01
        • 1970-01-01
        • 2020-05-31
        • 2016-12-17
        • 2020-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多