【问题标题】:Sequelize select only chosen attributesSequelize 仅选择选定的属性
【发布时间】:2018-08-09 16:11:57
【问题描述】:

我正在使用 MySQL 数据库,当我在做的时候:

models.modelA.findAll({
            attributes: [
               ['modelA.id','id']
            ],
            raw: true,
            include:
                [
                    {
                        model: models.modelB,
                        required: true
                    }
                ]

        }).then(function (tenants) {

        });

尽管我只选择了id,Sequelize 也在从相关表中检索所有属性,所以我得到了 {id, ... All attributes here}。

如何防止这种情况发生?有时我只想选择 2/3 列,而 Sequelize 总是选择所有无效的列。

【问题讨论】:

    标签: mysql express select model sequelize.js


    【解决方案1】:

    您可以执行以下操作

    models.modelA.findAll({
            attributes: [
               'id'
            ],
            raw: true,
            include:
                [
                    {
                        model: models.modelB,
                        attributes: ['fieldName1', 'fieldName2'], // Add column names here inside attributes array.
                        required: true
                    }
                ]
    
        }).then(function (tenants) {
    
        });
    

    【讨论】:

      【解决方案2】:

      您可以尝试发送空数组作为属性来排除它们:

      models.modelA.findAll({
                  attributes: [
                     ['modelA.id','id']
                  ],
                  raw: true,
                  include:
                      [
                          {
                              model: models.modelB,
                              attributes: [],
                              required: true
                          }
                      ]
      
              }).then(function (tenants) {
      
              });
      

      【讨论】:

        猜你喜欢
        • 2020-07-11
        • 1970-01-01
        • 2012-07-18
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 2012-06-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多