1

I have checked this answer and made sure with both scenario are correct. But still having issue creating constraints:

Model:

user.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    username: {
      type: DataTypes.STRING,
      unique: true,
      allowNull: false
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    }
  }, {});
  User.associate = function(models) {
    models.User.hasMany(models.Answer);
  };
  return User;
};

answer.js

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Answer = sequelize.define('Answer', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    userId: {
      type: DataTypes.INTEGER,
      references: {
        model: 'Users',
        key: 'id'
      },
     allowNull: true
    },
    content: DataTypes.TEXT
  }, {});
  Answer.associate = function(models) {
    models.belongsTo(models.User)
  };
  return Answer;
};

Migration

...-create-user.js

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      username: {
        type: Sequelize.STRING,
        unique: true,
        allowNull: false
      },
      password: {
        type: Sequelize.STRING,
        allowNull: false
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};

...create-answer.js

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Answers', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      userId: {
        allowNull: true,
        type: Sequelize.INTEGER
      },
      content: {
        allowNull: false,
        type: Sequelize.TEXT
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Answers');
  }
};

What else might be the issue? Is it due to allowNull: true? But I am sure this should not be the case because I also tested using allowNull: false if it works, but it did not.

I have also tried model: User and .INTEGER(11) exactly but nothing work. I cannot see foreign key constraints on PHPMyAdmin.

gacat
  • 116
  • 1
  • 13

1 Answers1

1

You should add

userId: {
      type: Sequelize.INTEGER,
      references: {
        model: 'Users',
        key: 'id'
      },
     allowNull: true
    }

in create-answer.js

instead of

userId: {
        allowNull: true,
        type: Sequelize.INTEGER
      },
Anatoly
  • 20,799
  • 3
  • 28
  • 42