question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Include not working on `hasOne` and `belongsTo`

See original GitHub issue

hi, how are you? i’m trying to get eager loading models but I don’t know what I’m doing wrong. I worked with v3 but v5 doesnt return associated models by eager loading.

// user model


const crypto = require('crypto');
const Sequelize = require('sequelize');
const zxcvbn = require('zxcvbn');

/**
 * User model Class
 * @class
 */
class User extends Sequelize.Model {
  /**
    * @param {object} props
  */
  constructor(props) {
    super(props);
  }
  /**
   * @param {object} sequelize - sequelize connection object
   * @param {object} DataTypes - sequelize datatypes definition
   * @return {Sequelize.Model} returns a new Sequelize db instance
   */
  static init(sequelize, DataTypes) {
    return super.init({
      email: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          isEmail: {
            args: true,
            msg: ' Invalid email format. please enter a valid email',
          },
        },
        unique: {
          msg: 'email already in use. please enter another email',
        },
      },
      password: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      name: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      lastname: {
        type: DataTypes.STRING,
        allowNull: false,
      },
      verified_email: {
        type: DataTypes.BOOLEAN,
        allowNull: false,
        defaultValue: false,
      },
      salt: {
        type: DataTypes.STRING(256),
        allowNull: false,
        validate: {
          isEmpty(value) {
            if (!value || value === '') {
              throw new Error('salt could not be empty. please enter a valid value');
            }
          },
        },
      },
      salt_rounds: {
        type: DataTypes.INTEGER,
        allowNull: false,
        validate: {
          isInt: {
            args: true,
            msg: 'salt rounds must be an integer, please enter a valid value',
          },
        },
      },
    }, {
      sequelize,
      paranoid: true,
      underscored: true,
    });
  }
  static associate(models) {
    models.User.belongsTo(models.Role, {
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
      foreignKey: {
        name: 'role_id',
        allowNull: false,
      },
    });
  }
}

module.exports = User;

// role model


const Sequelize = require('sequelize');

/**
 * User model Class
 * @class
 */
class Role extends Sequelize.Model {
  /**
  * @param {object} props
  */
  constructor(props) {
    super(props);
  }
  /**
   * @param {object} sequelize - sequelize connection object
   * @param {object} DataTypes - sequelize datatypes definition
   * @return {Sequelize.Model} returns a new Sequelize db instance
   */
  static init(sequelize, DataTypes) {
    return super.init({
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        set(value) {
          this.setDataValue('name', value.toLowerCase());
        },
      },
      slug_name: {
        type: DataTypes.STRING,
        allowNull: true,
        set(value) {
          this.setDataValue('slug_name', value.toLowerCase().replace(' ', '-'));
        },
      },
    }, {
      sequelize,
      paranoid: true,
      underscored: true,
    });
  }
  /**
   * @param {object} models - object that contains all defined models in the database
   */
  static associate(models) {
   models.Role.hasOne(models.User, {
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
      foreignKey: {
        name: 'role_id',
        allowNull: false,
      },
    });
  }
}

module.exports = Role;
// query method

const result = await models.User.findByPk(req.params.id, {
        include: [{
          model: models.Role,
        }],
        attributes: {
          exclude: ['salt', 'salt_rounds'],
        },
        rejectOnEmpty: true,
      });

To Reproduce Steps to reproduce the behavior:

  1. Define models User and Role (see above)
  2. create a role and a user with role_id
  3. run findByPk method with include on User
  4. See output

What do you expect to happen?

i want to get a property called Role inside my user result with eager loading information

What is actually happening?

the output is :

{
  "id": 1,
  "email": "asdrubalgranados@gmail.com",
  "password": "02f88a9c23429d594a8f5a54ca4e5f974cd75a4f0248f938e23e0763c23550312a7ba3e911bd42a2cc4ef8d2a75058ea119462a5f60d650a5deb2a42f0912057",
  "name": "asdrubal",
  "lastname": "granados",
  "verified_email": false,
  "createdAt": "2019-05-06T07:21:19.000Z",
  "updatedAt": "2019-05-06T07:21:19.000Z",
  "deletedAt": null,
  "role_id": 1
}

current excecuted sql by sequelize :

2019-05-06T08:15:03.487Z sequelize:sql:mysql Executed (default): SELECT `User`.`id`, 
`User`.`email`, `User`.`password`, `User`.`name`, `User`.`lastname`, 
`User`.`verified_email`, `User`.`created_at` AS `createdAt`, `User`.`updated_at` AS 
`updatedAt`, `User`.`deleted_at` AS `deletedAt`, `User`.`role_id`, `Role`.`id` AS `Role.id`,
 `Role`.`name` AS `Role.name`, `Role`.`slug_name` AS `Role.slug_name`, 
`Role`.`created_at` AS `Role.createdAt`, `Role`.`updated_at` AS `Role.updatedAt`, 
`Role`.`deleted_at` AS `Role.deletedAt` FROM `users` AS `User` LEFT OUTER JOIN `roles` 
AS `Role` ON `User`.`role_id` = `Role`.`id` AND (`Role`.`deleted_at` IS NULL) WHERE 
(`User`.`deleted_at` IS NULL AND `User`.`id` = '1');

Environment

Dialect: mysql

Dialect library version: mysql2 1.6.5 Database version: mysql 5.7.22 Sequelize version: 5.8.5 Node Version: 10.15.3 OS: mac os mojave

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
amgvcommented, May 12, 2019

@mickhansen can you help me with this? I asked this by slack channel but I got no answer

0reactions
github-actions[bot]commented, Nov 30, 2021

This issue has been automatically marked as stale because it has been open for 14 days without activity. It will be closed if no further activity occurs within the next 14 days. If this is still an issue, just leave a comment or remove the “stale” label. 🙂

Read more comments on GitHub >

github_iconTop Results From Across the Web

Sequelize include is not working with hasOne relationship
My problem is in my get request i am calling the profile picture model and including the users model, i get just my...
Read more >
hasOne() and belongsTo() not working in loopback4 #2209
I have create one simple api which is going to fetch the data from database(Mysql). Table 1 : person (id, person_name ) Table...
Read more >
hasOne relationship is not working well - Laracasts
hasOne relationship is not working well. Hi,. I have a database scheme for ... A car can have only one model, which model...
Read more >
Difference between has one belongs to and has many
If the users table has the account_id column then a User belongsTo Account. · But if the users table does not have the...
Read more >
How to use hasOne relationship in Laravel? - Rootstack
It should be noted that Laravel relationships do not create connections in ... In the above syntax, we have used the belongsTo method...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found