【问题标题】:Sequelize include query without child attributesSequelize 包含没有子属性的查询
【发布时间】:2022-01-12 01:45:37
【问题描述】:

我一直试图弄清楚当我不需要返回任何子属性时是否可以使用包含进行查询示例设置:

@Table
export class Parent extends Model {
 @PrimaryKey
 @Column
 ID: number
 ....
}

@Table
export class Child extends Model{
 @PrimaryKey
 @Column
 ID: number
 @PrimaryKey
 @BelongsTo(()=>Parent,{ as: 'parent', targetKey: 'ID', foreignKey: 'PARENT_ID' })
 @Column
 PARENT_ID: number
.....
}

然后在某个班级我跑

@Injectable()
export class ModelService {
  constructor(
    @InjectModel(Child)
    private childModel: typeof Child,
  ) {}

 findAll(){
   const res = this.childModel.findAll({
    attributes: [], //because I don't need any from child attributes
    include: Parent,
    .....,
   })
 }
}

虽然查询确实返回了结果,但 res 中每一行的 dataValues 属性是空的,我原以为每一行都会有 parent 属性。

即使我在查询中向子模型的属性键添加一列,它也会按预期工作。

关于如何解决这个问题的任何线索?

注意:我已经尝试在查询中将 required 放在父模型上。

【问题讨论】:

    标签: sequelize.js nestjs sequelize-typescript


    【解决方案1】:

    好像你需要使用join,像这样:

    const res = this.childModel.findAll({
      include: Parent,
      includeIgnoreAttributes: false,
    });
    
    

    【讨论】:

    • 嘿 @sptmru 感谢您的帮助,但 join 不是一个有效的选项 对象文字只能指定已知属性,并且类型 'FindOptions' 中不存在 'join'.ts(2345 )
    • @AmirShaneh 嘿!是的,那是错误的。请尝试更新的答案。
    • 再次感谢您的帮助,但这是另一个无效选项对象文字可能只指定已知属性,并且“FindOptions”类型中不存在“includeIgnoreAttributes”.ts(2345)跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    相关资源
    最近更新 更多