mysql - Sequelize 关联为一个模型创建 userId 和 user_id,但不为另一个模型创建 userId 和 user_id

标签 mysql node.js sequelize.js

两种模型“代理”和“代理”。每个都与我的“用户”模型相关联。我为每个模型指定了“user_id”的“foreignKey”。但是,Sequelize 会为一个模型在“user_id”之外创建一个“userId”,但不会为另一个模型创建一个“userId”,而在另一个模型中仅创建“user_id”。

编辑:

我的用户模型进行以下关联:

  User.associate = (models) => {
    User.hasMany(models.agency)
  }

  User.associate = (models) => {
    User.hasMany(models.agent)
  }

如何解决这个问题,使其没有“userId”?

目前,MySQL 中创建了以下表。

AGENCY

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| user_id   | int(11)      | YES  | MUL | NULL    |                |
| name      | varchar(255) | YES  |     | NULL    |                |
| address1  | varchar(255) | YES  |     | NULL    |                |
| address2  | varchar(255) | YES  |     | NULL    |                |
| city      | varchar(255) | YES  |     | NULL    |                |
| state     | varchar(255) | YES  |     | NULL    |                |
| zipCode   | varchar(255) | YES  |     | NULL    |                |
| country   | varchar(255) | YES  |     | NULL    |                |
| license   | varchar(255) | YES  |     | NULL    |                |
| createdAt | datetime     | NO   |     | NULL    |                |
| updatedAt | datetime     | NO   |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

AGENT

+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | int(11)      | NO   | PRI | NULL    | auto_increment |
| user_id   | int(11)      | YES  | MUL | NULL    |                |
| license   | varchar(255) | YES  |     | NULL    |                |
| headline  | varchar(255) | YES  |     | NULL    |                |
| createdAt | datetime     | NO   |     | NULL    |                |
| updatedAt | datetime     | NO   |     | NULL    |                |
| userId    | int(11)      | YES  | MUL | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

我的代码如下:

// FILE agency.js

module.exports = (sequelize, type) => {

  const Agency = sequelize.define('agency', {
    id: {
      type: type.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
    },
    user_id: {
      type: type.INTEGER,
      required: true
    },
    name: {
      type: type.STRING
    },
    address1: {
      type: type.STRING
    },
    address2: {
      type: type.STRING
    },
    city: {
      type: type.STRING
    },
    state: {
      type: type.STRING
    },
    zipCode: {
      type: type.STRING
    },
    country: {
      type: type.STRING
    },
    license: {
      type: type.STRING
    }
  },
  {
    freezeTableName: true,
  })

  Agency.associate = (models) => {
    Agency.belongsTo(models.user, {
      foreignKey: {
        name: 'user_id'
      }
    })
  }

  return Agency

}


// FILE agent.js

module.exports = (sequelize, type) => {

  const Agent = sequelize.define('agent', {
    id: {
      type: type.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      allowNull: false
    },
    user_id: {
      type: type.INTEGER,
      required: true
    },
    license: {
      type: type.STRING
    },
    headline: {
      type: type.STRING
    }
  },
  {
    freezeTableName: true,
  })

  Agent.associate = (models) => {
    Agent.belongsTo(models.user, {
      foreignKey: {
        name: 'user_id'
      }
    })
  }

  return Agent

}


// FILE db.js

const Sequelize = require('sequelize')
const config = require('../config').db

const db = {}

let sequelize = new Sequelize(config.database, config.username, config.password, config)

db.user = require('./user')(sequelize, Sequelize)
db.agency = require('./agency.js')(sequelize, Sequelize)
db.agent = require('./agent.js')(sequelize, Sequelize)

Object.keys(db).forEach(modelName => {
  if(db[modelName].associate) {
    db[modelName].associate(db)
  }
})

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db

最佳答案

您可能已经在您的用户模型中定义了这一点:

User.hasOne(Agent)
// In this case hasOne will add an attribute userId to the Agent model!

根据您的代码更改此:

User.hasMany(models.agency);
User.hasMany(models.agent);

致:

User.hasMany(models.agent,{foreignKey : 'user_id'});
User.hasMany(models.agency,{foreignKey : 'user_id'});

原因:如果您没有定义foreignKey,它将创建自己的userID

<小时/>

Difference between HasOne and BelongsTo: DOC REF

HasOne and BelongsTo insert the association key in different models from each other. HasOne inserts the association key in target model whereas BelongsTo inserts the association key in the source model.

When information about association is present in source model we can use belongsTo. In this case Player is suitable for belongsTo because it has teamId column.

Player.belongsTo(Team)  // `teamId` will be added on Player / Source model

When information about association is present in target model we can use hasOne. In this case Coach is suitable for hasOne because Team model store information about its Coach as coachId field.

Coach.hasOne(Team)  // `coachId` will be added on Team / Target model

关于mysql - Sequelize 关联为一个模型创建 userId 和 user_id,但不为另一个模型创建 userId 和 user_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57554744/

相关文章:

Node.js 生成进程在 Docker 容器内不工作

node.js - 添加一个更改基本路由的快速使用处理程序

node.js - 我无法通过 sequelize 进行基本的 sql 查询

node.js - 如何限制 Sequelize 上的多对多关系

javascript - 用户获取请求时出错

php - 多个 mysql 语句未通过 php 执行(语句通过 phpmyadmin 运行)

php - 如何在 MySQL 中只返回一次列值

javascript - 在多个 Browserify 或 Webpack 包中共享通过 NPM 加载的模块的简单解决方案

php - 阅读 SELECT LAST_INSERT_ID(),这似乎产生了一个数组

MySQL:如何对多列的每列求和