【问题标题】:Sequelize query belongstomany not including child attributesSequelize query belongstoany 不包括子属性
【发布时间】:2018-04-07 01:17:01
【问题描述】:

我是 sequelize 的新手,并试图确定如何对归属关系执行查询,我需要检查子关系是否存在,但我不想带来它的任何字段。

  Project.belongsToMany(models.User, {
        through: 'userproject', as: 'links', foreignKey: 'project_id', otherKey: 'user_id'
    });

我的尝试:

  const linkedProjects = this.model.findAll({
        attributes: ['Project.*'],
        include: [{
            model: models.User,
            as: 'links',
            where: {
                userid: user.sub
            }
        }]
    });

但是这仍然给我带来了预计的链接数据,除了 where 部分之外,这对我来说没用。

没有“原始查询”的最佳方法是什么? 我正在寻找,基本上:

select p.* from project p 
inner join userproject up on p.project_id = up.project_id 
inner join user u on up.user_id = u.id
where u.userid = 'xxx'

【问题讨论】:

  • 您是否尝试在include 数组中的对象内添加attributes: []
  • 那行得通。想把它作为答案,以便我可以接受吗?谢谢
  • 我刚刚添加它作为答案:)

标签: sequelize.js has-and-belongs-to-many


【解决方案1】:

重新迭代以将其标记为解决方案。

解决办法是在sequelize操作中添加attributes: []不检索列。 attributes 字段是一个数组,其中包含在执行 sequelize 操作时必须检索的列名。

  const linkedProjects = this.model.findAll({
        attributes: ['Project.*'],
        include: [{
            model: models.User,
            as: 'links',
            attributes: [],
            where: {
                userid: user.sub
            }
        }]
    });

【讨论】:

    【解决方案2】:

    而不是这个:

    attributes: ['Project.*'], // this will load only fields from project table
    

    使用

    this.model.findAll({
        attributes: ['id','title',...], // all the attributes from project table
        include: [{
            model: models.User,
            attributes: ['id','project_id' ,], // all the attributes from user table
            as: 'links',
            where: {
                userid: user.sub
            }
        }]
    });
    
    //OR 
    
    // remove attributes from all
    this.model.findAll({
        include: [{
            model: models.User,
            as: 'links',
            where: {
                userid: user.sub
            }
        }]
    });
    

    【讨论】:

      猜你喜欢
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      相关资源
      最近更新 更多