Node.js顺序化从其他模型中提取虚拟列的值

时间:2019-05-15 12:21:11

标签: mysql node.js orm sequelize.js

我正在使用Sequelize 5.7,试图利用虚拟数据类型,
将相关信息纳入模型。

给出简化的companyuser模型,如何获得company.name
进入user.companyname吗?

公司

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

用户

  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'
          }
      }
    }
  );

2 个答案:

答案 0 :(得分:2)

对于您而言,我认为使用关系(关联)是一个更好的主意

Sequelize Associations

User.findAll({ include: Company }).then(users => console.log(users));

然后,在调用模型时,您将执行以下操作:

wsimport -s src <wsdl url>

答案 1 :(得分:1)

我通过在模型中使用 type: DataTypes.VIRTUAL 解决了这个问题

const { Model, DataTypes } = require('sequelize');

class User extends Model {
    static init(sequelize) {
        super.init({
            id: {
                type: DataTypes.INTEGER.UNSIGNED,
                autoIncrement: true,
                primaryKey: true
            },
            login: {
                type: DataTypes.STRING(45),
                unique: true
            },
            company_id: {
                type: DataTypes.INTEGER.UNSIGNED,
            },
            companyname:{
                type: DataTypes.VIRTUAL,
                get() {
                    return this.Company?.get().name;
                },
                set(/*value*/) {
                    throw new Error('Do not try to set the `companyname` value!');
                }
            },
        }, {
            sequelize
        })
    }
    static associate(models) {
        this.belongsTo(Company, {
          foreignKey: 'company_id',
        });
    }
}

module.exports = User;

搜索只包括关联:

User.findAll({ include: Company })

我通常在不同文件中使用“class”创建每个模型,但如果您需要,只需在@jalex19 解决方案中包含以下代码

companyname:{
    type: DataTypes.VIRTUAL,
    get() {
        return this.Company?.get().name;
    },
    set(/*value*/) {
        throw new Error('Do not try to set the `fullName` value!');
    }
},