Nikito4ka_ka
@Nikito4ka_ka

Как решить проблему с добавлением ассоциаций в mysql (используя sequelize)?

Здравствуйте, создаю две таблицы `user` и `userInfo`, но на последней migration вылезает ошибка:
Loaded configuration file "database/config.json".
Using environment "development".
== 20230226102752-user-to-user-info: migrating =======

ERROR: Cannot add foreign key constraint


Сначала создается таблица `user`, потом создается таблица `userInfo`, а уже потом добавляются столбцы отвечающие за связь.


в файле `migration association-user-and-userInfo` пробовал 2 вариации добавления столбцов:
1. при использовании transaction выполнялись все миграции (включая последнюю где добавляются столбцы зависимостей). Никаких ошибок не выдает, но и в phpMyAdmin не отображаются эти столбцы! как будто их и не добавлял! (пробовал обновлять структуру, перезагружать сервер с mysql не помогает).
2. А вот уже вторая вариация без transaction которая написана ниже в файле выдает ошибку которую указал выше.

Помогите пожалуйста разобраться и понять в что же я делаю не так! За ранее спасибо!

Все файлы:
migrations create-user

'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
	async up(queryInterface, Sequelize) {
		await queryInterface.createTable('user', {
			id: {
				allowNull: false,
				autoIncrement: true,
				primaryKey: true,
				type: Sequelize.INTEGER,
			},
			name: {
				type: Sequelize.STRING(255),
				required: true,
			},
			email: {
				type: Sequelize.STRING(255),
				unique: true,
				required: true,
			},
			password: {
				type: Sequelize.STRING(255),
				required: true,
			},
			role: {
				type: Sequelize.STRING(20),
				allowNull: false,
				defaultValue: 'USER',
			},
		});
	},
	async down(queryInterface, Sequelize) {
		await queryInterface.dropTable('user');
	},
};


migration create-userInfo

'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
	async up(queryInterface, Sequelize) {
		await queryInterface.createTable('userInfo', {
			id: {
				allowNull: false,
				autoIncrement: true,
				primaryKey: true,
				type: Sequelize.INTEGER,
			},
			phone: {
				type: Sequelize.STRING(255),
				unique: true,
			},
			languages: {
				type: Sequelize.STRING(255),
				// required: true,
			},
			imageUrl: {
				type: Sequelize.TEXT('long'),
				allowNull: false,
			},
		});
	},
	async down(queryInterface, Sequelize) {
		await queryInterface.dropTable('userInfo');
	},
};


migration association-user-and-userInfo

'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
	async up(queryInterface, Sequelize) {
		// const transaction = await queryInterface.sequelize.transaction();
		// try {
		// 	await queryInterface.addColumn(
		// 		'user',
		// 		'userInfoId',
		// 		{
		// 			type: Sequelize.BIGINT(20).UNSIGNED,
		// 			allowNull: false,
		// 			references: {
		// 				model: 'userInfo',
		// 				key: 'id',
		// 			},
		// 			onDelete: 'CASCADE',
		// 		},
		// 		{ transaction }
		// 	);
		// 	await queryInterface.addColumn(
		// 		'userInfo',
		// 		'userId',
		// 		{
		// 			type: Sequelize.BIGINT(20).UNSIGNED,
		// 			allowNull: false,
		// 			references: {
		// 				model: 'user',
		// 				key: 'id',
		// 			},
		// 			onDelete: 'CASCADE',
		// 		},
		// 		{ transaction }
		// 	);
		// 	await transaction.commit();
		// } catch (error) {
		// 	await transaction.rollback();
		// }

		await queryInterface.addColumn('user', 'userInfoId', {
			type: Sequelize.BIGINT(20).UNSIGNED,
			allowNull: false,
			references: {
				model: 'userInfo',
				key: 'id',
			},
			onDelete: 'CASCADE',
		});

		await queryInterface.addColumn('userInfo', 'userId', {
			type: DataTypes.BIGINT(20).UNSIGNED,
			allowNull: false,
			references: {
				model: 'user',
				key: 'id',
			},
			onDelete: 'CASCADE',
		});
	},

	async down(queryInterface, Sequelize) {
		// const transaction = await queryInterface.sequelize.transaction();

		// try {
		await queryInterface.removeColumn('user', 'infoUserId');
		await queryInterface.removeColumn('userInfo', 'userId');

		// 	await transaction.commit();
		// } catch (error) {
		// 	await transaction.rollback();
		// }

		/**
		 * Add reverting commands here.
		 *
		 * Example:
		 * await queryInterface.dropTable('users');
		 */
	},
};


model user

'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
	class User extends Model {
		/**
		 * Helper method for defining associations.
		 * This method is not a part of Sequelize lifecycle.
		 * The `models/index` file will call this method automatically.
		 */
		static associate(models) {
			// define association here
			User.hasOne(models.UserInfo, {
				foreignKey: 'userInfoId',
				onDelete: 'CASCADE',
			});
		}
	}
	User.init(
		{
			Name: DataTypes.STRING(255),
			email: DataTypes.STRING(255),
			password: DataTypes.STRING(255),
			role: DataTypes.STRING(20),
			userInfoId: DataTypes.BIGINT(20).UNSIGNED,
		},
		{
			sequelize,
			modelName: 'User',
		}
	);

	return User;
};


model userInfo

'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
	class UserInfo extends Model {
		/**
		 * Helper method for defining associations.
		 * This method is not a part of Sequelize lifecycle.
		 * The `models/index` file will call this method automatically.
		 */
		static associate(models) {
			// define association here
			UserInfo.belongsTo(models.User, {
				foreignKey: 'userId',
				onDelete: 'CASCADE',
			});
		}
	}
	UserInfo.init(
		{
			phone: DataTypes.STRING(255),
			languages: DataTypes.STRING(255),
			imageUrl: DataTypes.TEXT('long'),
			userId: DataTypes.BIGINT(20).UNSIGNED,
		},
		{
			sequelize,
			modelName: 'UserInfo',
		}
	);
	return UserInfo;
};

  • Вопрос задан
  • 38 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы