Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Sequelize virtual column pulling value from other model

I'm working with Sequelize 5.7, trying to utilize virtual datatype,
to pull related information into a model.

Given simplified company and user models, how do I get company.name
into user.companyname ?

company

  let Schema = sequelize.define(
    "company",
    {
      id: {
        type: DataTypes.INTEGER.UNSIGNED,
        autoIncrement: true,
        primaryKey: true
      },
      name: {
        type: DataTypes.STRING(45)
      }
    }
  );

user

  let Schema = sequelize.define(
    "user",
    {
      id: {
        type: DataTypes.INTEGER.UNSIGNED,
        autoIncrement: true,
        primaryKey: true
      },
      login: {
        type: DataTypes.STRING(45),
        unique: true
      },
      company: {
          type: DataTypes.INTEGER.UNSIGNED,
          references: {
            model: sequelize.model('company'),
            key: 'id'
          }
      },

      /* This companyname contruct is pure fantasy, and the target of my question */

      companyname: {
        type: new DataTypes.VIRTUAL(DataTypes.STRING,['company']),
          references: {
            model: 'company',
            key: 'name'
          }
      }
    }
  );
like image 474
Mogens TrasherDK Avatar asked Oct 29 '25 02:10

Mogens TrasherDK


1 Answers

In your case, I think it is a better idea to use a relationship (an association)

Sequelize Associations

const User = sequelize.define('user', {
  id: {
    type: DataTypes.INTEGER.UNSIGNED,
    autoIncrement: true,
    primaryKey: true
  },
  login: {
    type: DataTypes.STRING(45),
    unique: true
  },
  company_id: {
    type: DataTypes.INTEGER.UNSIGNED,
  },
});

const Company = sequelize.define('company', {
  id: {
    type: DataTypes.INTEGER.UNSIGNED,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
  },
});

User.belongsTo(Company, {
  foreignKey: 'company_id', // you can use this to customize the fk, default would be like companyId
});

Company.hasMany(User);

Then when calling your model you do something like:

User.findAll({ include: Company }).then(users => console.log(users));
like image 133
jalex19 Avatar answered Oct 31 '25 16:10

jalex19