Skip to content

Another BAD_FIELD_ERROR unknown column in ORDER clause here #6891

Closed

Description

@zenithtekla

How to use include.limit, include.order and include.separate? I tried putting limit and order in the following ways. See the 2 methods. The getLastDossierTwoQueries gives me the wanted result but it takes 2 queries to do that. I want to still get that expected outcome by EagerLoading.

What you are doing? Sequelize with MySQL on NodeJS backend NESA2.

'use strict';

module.exports = function(sequelize, DataTypes) {
  var Schema = sequelize.define('ECMS_Dossier', {
      file_id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      file: DataTypes.BLOB(),
      filename: DataTypes.STRING(100),
      time_field: DataTypes.DATE()
    },
    {
      tableName: 'ECMS_dossier_table',
      freezeTableName: true,
      charset: 'utf8',
      collate: 'utf8_unicode_ci',
      classMethods: {
        associate: function(models){
          Schema.belongsTo(models.ECMS_Equipment, { foreignKey: 'asset_number', targetKey: 'asset_number', onDelete: 'CASCADE'});
        }
      }
    });

  Schema.removeAttribute('id');
  return Schema;
};

'use strict';

module.exports = function(sequelize, DataTypes) {
  var Schema = sequelize.define('ECMS_Equipment' , {
      model: {
        type: DataTypes.STRING(20) ,
        allowNull: false
      },
      asset_number: {
        type: DataTypes.STRING(20),
        allowNull: false,
        unique: true,
        primaryKey:true
      },
      last_cal: DataTypes.DATE(),
      schedule: DataTypes.INTEGER(20),
      next_cal: DataTypes.DATE(),
      status: {
        type: DataTypes.INTEGER(2).UNSIGNED,
        defaultValue: 1
      }
    } ,
    {
      timestamps: false ,
      tableName: 'ECMS_equipment_table' ,
      freezeTableName: true ,
      charset: 'utf8' ,
      collate: 'utf8_unicode_ci',
      getterMethods: {
        equipmentInfo: function () {
          return 'model: [' + this.model + '] - asset: [' + this.asset_number + ']';
        },
        retrieveLocation: function (models) {
                  // trying to implement
        }
      },
      classMethods: {
        associate: function(models){
          // by default, will reference to targetKey of primary id in the Location table
          // belongsTo - foreignKey sits on the source table: which is this Schema
          Schema.belongsTo(models.ECMS_Location, { foreignKey: 'asset_id', targetKey: 'id', onDelete: 'CASCADE' } );
          Schema.hasMany(models.ECMS_Dossier, { foreignKey: 'asset_number', onDelete: 'CASCADE'});
        }
      }
    });

  Schema.removeAttribute('id');
  return Schema;
};

'use strict';

module.exports = function(sequelize, DataTypes) {
  var Schema = sequelize.define('ECMS_Location', {
      desc: {
        type: DataTypes.STRING(20),
        //notEmpty: true,
        allowNull: false/*,
        get: function () {
          return this.getDataValue('desc');
        }*/
      }
    },
    {
      timestamps: false,
      tableName: 'ECMS_location_table',
      freezeTableName: true,
      charset: 'utf8',
      collate: 'utf8_unicode_ci',
      classMethods: {
        associate: function(models){
          // hasOne - foreignKey sits on the Equipment (target) table, this Schema is the source table
          Schema.hasOne(models.ECMS_Equipment, { foreignKey: 'asset_id', onDelete: 'CASCADE' } );
        }
      },
      getterMethods: {
        getLocation: function () {
          return ' - location: [' + this.desc + ']';
        }
      }
    });

  return Schema;
};
  function getLastDossierTwoQueries(req, res, next){
    ECMS_Equipment.findOne({
      where: req.params,
      attributes: ['asset_id', 'model', 'asset_number', 'last_cal', 'schedule', 'next_cal'],
      include: [
        { model: ECMS_Location, attributes: ['desc']}
      ]
    }).then(function(result){
      var record = result.dataValues;
      ECMS_Dossier.findAll({
        where: {asset_number: record.asset_number},
        attributes: ['time_field', 'file_id', 'filename', 'createdAt', 'updatedAt', 'file'],
        limit: 1,
        order: [ ['time_field', 'DESC'] ]
      }).then(function(result){
        record.ECMS_Dossiers = _.has(result, 'dataValues') ? result.dataValues : result;
        res.json(record);
      }).catch(_errorHandler);
    }).catch(_errorHandler);
  }

  function getlastDossierEagerLoading(req, res, next){
    ECMS_Equipment.findOne({
      where: req.params,
      attributes: ['asset_id', 'model', 'asset_number', 'last_cal', 'schedule', 'next_cal'],
      include: [
        { model: ECMS_Location, attributes: ['desc']},
        { 
             model: ECMS_Dossier, 
             attributes: ['time_field', 'file_id', 'filename', 'createdAt', 'updatedAt', 'file'], 
             limit: 1
        }
      ],
      // limit: [ [ECMS_Dossier, 1] ], problem is the limit option does not support on associated model, resort to include.separate?
      order: [ [{model: ECMS_Dossier}, 'time_field', 'DESC'] ] // orderBy is fine.
    }).then(function(result){
      res.json(result.dataValues);
    }).catch(function(err){res.json(err);});
  }

The association goes like: 1 equipment has 1 location, 1 equipment hasMany dossiers. MongoDB of the SQL relation looks like:

var Schema = new Schema({
  equipment_model: String,
  asset_id: Number,
  asset_number: String,
  last_cal: Date ,
  schedule: Number ,
  next_cal: Date ,
  dossiers: [{
    file_id: Number,
    filename: String,
    file: {
      name: String ,
      data: Buffer ,
      contentType: String
    },
    time_field: Date,
    createdAt: Date,
    updatedAt: Date
  }],
  location: {
    id: Number,
    desc: String
  }
});

What do you expect to happen?

I want to use include.limit for associated model: Dossier to get the record 1 equipment and 1 latest Dossier.

{
	"asset_id": 19,
	"model": "brts37",
	"asset_number": "11",
	"last_cal": "2016-02-22T08:00:00.000Z",
	"schedule": 9,
	"next_cal": "2017-07-17T07:00:00.000Z",
	"ECMS_Dossiers": [
		{
			"time_field": "2041-02-04T04:05:58.000Z",
			"asset_number": "11",
			"createdAt": "2016-11-19T01:34:43.000Z",
			"file_id": 46,
			"filename": "Oslo_file110",
			"updatedAt": "2016-11-19T01:34:43.000Z",
			"file": {
				"type": "Buffer",
				"data": [
					79,
					115,
					108,
					111,
					95,
					102,
					105,
					108,
					101,
					49,
					49,
					48
				]
			}
		}
	],
	"ECMS_Location": {
		"getLocation": " - location: [Oslo]",
		"desc": "Oslo"
	}
}

What is actually happening? Output in JSON denoting the Unknown column 'ECMS_Dossiers.time_field' error as follow:

Output, either JSON or SQL

{
"name": "SequelizeDatabaseError",
"message": "ER_BAD_FIELD_ERROR: Unknown column 'ECMS_Dossiers.time_field' in 'order clause'",
"parent": {
"code": "ER_BAD_FIELD_ERROR",
"errno": 1054,
"sqlState": "42S22",
"index": 0,
"sql": "SELECT `ECMS_Equipment`.`asset_id`, `ECMS_Equipment`.`model`, `ECMS_Equipment`.`asset_number`, `ECMS_Equipment`.`last_cal`, `ECMS_Equipment`.`schedule`, `ECMS_Equipment`.`next_cal`, `ECMS_Location`.`id` AS `ECMS_Location.id`, `ECMS_Location`.`desc` AS `ECMS_Location.desc` FROM `ECMS_equipment_table` AS `ECMS_Equipment` LEFT OUTER JOIN `ECMS_location_table` AS `ECMS_Location` ON `ECMS_Equipment`.`asset_id` = `ECMS_Location`.`id` WHERE `ECMS_Equipment`.`asset_id` = '19' ORDER BY `ECMS_Dossiers`.`time_field` DESC LIMIT 1;"
},
"original": {
"code": "ER_BAD_FIELD_ERROR",
"errno": 1054,
"sqlState": "42S22",
"index": 0,
"sql": "SELECT `ECMS_Equipment`.`asset_id`, `ECMS_Equipment`.`model`, `ECMS_Equipment`.`asset_number`, `ECMS_Equipment`.`last_cal`, `ECMS_Equipment`.`schedule`, `ECMS_Equipment`.`next_cal`, `ECMS_Location`.`id` AS `ECMS_Location.id`, `ECMS_Location`.`desc` AS `ECMS_Location.desc` FROM `ECMS_equipment_table` AS `ECMS_Equipment` LEFT OUTER JOIN `ECMS_location_table` AS `ECMS_Location` ON `ECMS_Equipment`.`asset_id` = `ECMS_Location`.`id` WHERE `ECMS_Equipment`.`asset_id` = '19' ORDER BY `ECMS_Dossiers`.`time_field` DESC LIMIT 1;"
},
"sql": "SELECT `ECMS_Equipment`.`asset_id`, `ECMS_Equipment`.`model`, `ECMS_Equipment`.`asset_number`, `ECMS_Equipment`.`last_cal`, `ECMS_Equipment`.`schedule`, `ECMS_Equipment`.`next_cal`, `ECMS_Location`.`id` AS `ECMS_Location.id`, `ECMS_Location`.`desc` AS `ECMS_Location.desc` FROM `ECMS_equipment_table` AS `ECMS_Equipment` LEFT OUTER JOIN `ECMS_location_table` AS `ECMS_Location` ON `ECMS_Equipment`.`asset_id` = `ECMS_Location`.`id` WHERE `ECMS_Equipment`.`asset_id` = '19' ORDER BY `ECMS_Dossiers`.`time_field` DESC LIMIT 1;"
}

Dialect: mysql
Database version: MySQL 5.5
Sequelize version: 3.27.0

Activity

  1. zenithtekla commented on Nov 19, 2016

    @zenithtekla
    Author

    I narrow the issue and renamed/shortened generated queries to make comparison
    WITHOUT limit: 1

    SELECT `Equipment`.*, `Location`.`id` AS `Location.id`, `Location`.`desc` AS `Location.desc`, `Dossiers`.`time_field` AS `Dossiers.time_field`, `Dossiers`.`file_id` AS `Dossiers.file_id`, `Dossiers`.`filename` AS `Dossiers.filename`, `Dossiers`.`createdAt` AS `Dossiers.createdAt`, `Dossiers`.`updatedAt` AS `Dossiers.updatedAt`, `Dossiers`.`file` AS `Dossiers.file` FROM (SELECT `Equipment`.`asset_id`, `Equipment`.`model`, `Equipment`.`asset_number`, `Equipment`.`last_cal`, `Equipment`.`schedule`, `Equipment`.`next_cal` FROM `Equipment_table` AS `Equipment` WHERE `Equipment`.`asset_id` = '19' LIMIT 1) AS `Equipment` LEFT OUTER JOIN `Location_table` AS `Location` ON `Equipment`.`asset_id` = `Location`.`id` LEFT OUTER JOIN `ECMS_dossier_table` AS `Dossiers` ON `Equipment`.`asset_number` = `Dossiers`.`asset_number` ORDER BY `Dossiers`.`time_field` DESC;
    
    // BEAUTIFIERED w/ http://www.dpriver.com/pp/sqlformat.htm
    SELECT `Equipment`.*, 
           `Location`.`id`         AS `Location.id`, 
           `Location`.`desc`       AS `Location.desc`, 
           `Dossiers`.`time_field` AS `Dossiers.time_field`, 
           `Dossiers`.`file_id`    AS `Dossiers.file_id`, 
           `Dossiers`.`filename`   AS `Dossiers.filename`, 
           `Dossiers`.`createdat`  AS `Dossiers.createdAt`, 
           `Dossiers`.`updatedat`  AS `Dossiers.updatedAt`, 
           `Dossiers`.`file`       AS `Dossiers.file` 
    FROM   (SELECT `Equipment`.`asset_id`, 
                   `Equipment`.`model`, 
                   `Equipment`.`asset_number`, 
                   `Equipment`.`last_cal`, 
                   `Equipment`.`schedule`, 
                   `Equipment`.`next_cal` 
            FROM   `equipment_table` AS `Equipment` 
            WHERE  `Equipment`.`asset_id` = '19' 
            LIMIT  1) AS `Equipment` 
           LEFT OUTER JOIN `location_table` AS `Location` 
                        ON `Equipment`.`asset_id` = `Location`.`id` 
           LEFT OUTER JOIN `ecms_dossier_table` AS `Dossiers` 
                        ON `Equipment`.`asset_number` = `Dossiers`.`asset_number` 
    ORDER  BY `Dossiers`.`time_field` DESC; 

    With limit:1, the query seems to generated half-way and stop there.

    SELECT `Equipment`.`asset_id`, `Equipment`.`model`, `Equipment`.`asset_number`, `Equipment`.`last_cal`, `Equipment`.`schedule`, `Equipment`.`next_cal`, `Location`.`id` AS `Location.id`, `Location`.`desc` AS `Location.desc` FROM `Equipment_table` AS `Equipment` LEFT OUTER JOIN `Location_table` AS `Location` ON `Equipment`.`asset_id` = `Location`.`id` WHERE `Equipment`.`asset_id` = '19' ORDER BY `Dossiers`.`time_field` DESC LIMIT 1;
    
    // BEAUTIFIERED w/ http://www.dpriver.com/pp/sqlformat.htm
    
    SELECT `Equipment`.`asset_id`, 
           `Equipment`.`model`, 
           `Equipment`.`asset_number`, 
           `Equipment`.`last_cal`, 
           `Equipment`.`schedule`, 
           `Equipment`.`next_cal`, 
           `Location`.`id`   AS `Location.id`, 
           `Location`.`desc` AS `Location.desc` 
    FROM   `equipment_table` AS `Equipment` 
           LEFT OUTER JOIN `location_table` AS `Location` 
                        ON `Equipment`.`asset_id` = `Location`.`id` 
    WHERE  `Equipment`.`asset_id` = '19' 
    ORDER  BY `dossiers`.`time_field` DESC 
    LIMIT  1; 
  2. zenithtekla commented on Nov 19, 2016

    @zenithtekla
    Author

    I changed table names and use MySQL client to test:

    SELECT `Equipment`.*, 
           `Location`.`id`         AS `Location.id`, 
           `Location`.`desc`       AS `Location.desc`, 
           `Dossiers`.`time_field` AS `Dossiers.time_field`, 
           `Dossiers`.`file_id`    AS `Dossiers.file_id`, 
           `Dossiers`.`filename`   AS `Dossiers.filename`, 
           `Dossiers`.`createdat`  AS `Dossiers.createdAt`, 
           `Dossiers`.`updatedat`  AS `Dossiers.updatedAt`, 
           `Dossiers`.`file`       AS `Dossiers.file` 
    FROM   (SELECT `Equipment`.`asset_id`, 
                   `Equipment`.`model`, 
                   `Equipment`.`asset_number`, 
                   `Equipment`.`last_cal`, 
                   `Equipment`.`schedule`, 
                   `Equipment`.`next_cal` 
            FROM   `ecms_equipment_table` AS `Equipment` 
            WHERE  `Equipment`.`asset_id` = '19' 
            LIMIT  1) AS `Equipment` 
           LEFT OUTER JOIN `ecms_location_table` AS `Location` 
                        ON `Equipment`.`asset_id` = `Location`.`id` 
           LEFT OUTER JOIN `ecms_dossier_table` AS `Dossiers` 
                        ON `Equipment`.`asset_number` = `Dossiers`.`asset_number` 
    ORDER  BY `Dossiers`.`time_field` DESC;

    The query above works fine. I was expecting LIMIT 1 at the end of the query and adding LIMIT 1 manually myself, the query doesn't result in any error. Problem is Sequelize didn't result in the expected behavior in this case.

  3. alixanyan commented on Mar 29, 2018

    @alixanyan

    👎 Some issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions