mysql - 没有外键的关联并在表中加入

标签 mysql model sequelize.js associations

我正在研究 Node + sequelize + mysql。所有的事情在我的代码中都运行良好。现在我需要在列表页面中添加搜索字段。在此搜索页面中,会显示用户的名字、姓氏、公司名称和状态。我从一张表中获取了所有数据,但公司来自“公司”表。在用户表中有 company_id。我无法为 company_id 建立关联。现在我也想从 company_name 搜索。我如何添加没有关联的包含。

const { User, Company } = require("../models"); 

if(query.trim() != "") { 
        [err, users] = await to(User.findAll({
            where : {[Op.or] : {first_name:{ [Op.like]: '%'+query.trim()+'%' },last_name:{ [Op.like]: '%'+query.trim()+'%' }}}, 
            include : [
                {
                    model:Company,
                    where : {company_name:{ [Op.like]: '%'+query.trim()+'%' }}
                }],
            limit: 5,
            offset: 0,
            order: [[id, ASC]]
        }));
        console.log('err ----------------',err);
        console.log(users);
}

我从上面的代码中得到以下错误:
err ---------------- { filename:
   '/var/www/html/fullproject-name/backend/node_modules/sequelize/lib/model.js',
  line: 583,
  row: 13,
  message: 'Company is not associated to User!',
  type: 'SequelizeEagerLoadingError',
  stack:
   'SequelizeEagerLoadingError: Company is not associated to User!\n    at Function._getIncludedAssociation..... }

用户型号代码:
module.exports = (sequelize, DataTypes) => {
    var Model = sequelize.define('User', { 
        email: {type: DataTypes.STRING, allowNull: true, unique: true, validate: { isEmail: {msg: "Phone number invalid."} }}, 
        company_id: DataTypes.INTEGER,
        first_name: DataTypes.STRING,
        last_name: DataTypes.STRING, 
        active:DataTypes.INTEGER, 
    });

}

公司型号代码:
module.exports = (sequelize, DataTypes) => {
  var Model = sequelize.define('Company', {
    company_name: DataTypes.STRING, 
    company_attachment: DataTypes.STRING,
  });
   }

最佳答案

您需要相互使用 associate your models 以便能够与连接一起查询它们。在下面的示例中,我为 UserCompany 添加了一些关联。我定义的关系(您可以更改)是一对多的。一个用户属于一个公司;一个公司有很多用户。

这个关联会将 company_id 的外键放在 User 模型上。

const models = require("./models.js") // Update if necessary
module.exports = (sequelize, DataTypes) => {
  var User = sequelize.define("User", { // Changed from Model to User
    email: {
      type: DataTypes.STRING,
      allowNull: true,
      unique: true,
      validate: { isEmail: { msg: "Phone number invalid." } }
    },
    company_id: DataTypes.INTEGER,
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    active: DataTypes.INTEGER
  });

  User.belongsTo(models.Company); // User to Company association
};

const models = require("./models.js") // Update if necessary
module.exports = (sequelize, DataTypes) => {
  var Company = sequelize.define("Company", { // Changed from Model to Company
    company_name: DataTypes.STRING,
    company_attachment: DataTypes.STRING
  });

  Company.hasMany(models.User); // Company to User association
};

关于mysql - 没有外键的关联并在表中加入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57141999/

相关文章:

mysql - 如果存在则插入更新

python - 引发 ImportError "Settings cannot be imported"ENVIRONMENT_VARIABLE

cakephp - cakephp中单个表上的许多模型

mysql - 在 MySQL 中创建加密

javascript - 更新名称未知的对象的模型值

model - Doctrine - 检查记录的最佳方法,然后更新或添加

node.js - Sequelize @6.3.4 无法连接到 docker -> postgres

migration - Sequelize 迁移将 Sequelize.UUID 主键字段转换为 MYSQL 中的整数自动增量

mysql - 使用 Sequelize 事务记录对象数组

MYSQL触发器/约束在另一列中设置相等的列值