Проседение BulkCreate не удастся с дублирующей ошибкой ввода, несмотря на не-дубликационные данные и обновленные уникальMySql

Форум по Mysql
Ответить
Anonymous
 Проседение BulkCreate не удастся с дублирующей ошибкой ввода, несмотря на не-дубликационные данные и обновленные уникаль

Сообщение Anonymous »

Я пытаюсь перенести набор данных в базе данных MySQL, который является ROLE_ID и MODULE_ID Тот же MySQL отказывается хранить Showing < /p>
sqlmessage: "Duplicate '3-1' для ключа 'role_module_bridge.role_module_bridge_module_role_role_role_role_role_bridge.role_module_bridge_module_role_role_role_role_bridge. "Вставьте в ROLE_MODULE_BRIDGE (,

Код: Выделить всё

module_id
,,

Код: Выделить всё

permission_id
,

Код: Выделить всё

createdAt
,

Код: Выделить всё

updatedAt
) Значения (NULL, 3,1,2, '2025-09-15 19:19:37', '2025-09-15 19:19:37'), (NULL, 3,1,3, '2025-09-15 19:19:37', '2025-09-15 19:19:37'); Данные < /p>
[
{ role_id: 1, module_id: 3, permission_id: 2 },
{ role_id: 1, module_id: 3, permission_id: 3 }
]
< /code>
async function grant(
roleName: string,
moduleNames: string[],
permissionNames: string[]
) {
const { Role, Modules, Permission, RoleModuleBridge } = await import(
'../src/models/index'
);

const role = await Role.findOne({ where: { role: roleName }, raw: true });
const mods = await Modules.findAll({
where: { module_name: moduleNames } as any,
raw: true,
});

const perms = await Permission.findAll({
where: { permission_name: permissionNames } as any,
raw: true,
});

console.log("role: ", role);
console.log("module: ", mods);
console.log("permission: ", perms);
console.log(permissionNames);

const rows = [];
for (const m of mods) {
for (const p of perms) {
rows.push({
role_id: role?.id,
module_id: m?.id,
permission_id: p?.id,
});
}
}

console.log(rows);
await RoleModuleBridge.bulkCreate(rows);
}
< /code>
RoleModuleBridge Model
import sequelize from '@/lib/sequelize';
import { Model, Optional, DataTypes } from 'sequelize';

export interface RoleModulesBridgeAttributes {
id: number;
module_id: number;
role_id: number;
permission_id: number;
}

export interface RoleModulesBridgeCreationAttributes
extends Optional {}

const RoleModuleBridge = sequelize.define<
Model
>(
'RoleModuleBridge',
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
module_id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
references: {
model: 'modules',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'RESTRICT',
},
role_id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
references: {
model: 'roles',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'RESTRICT',
},
permission_id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
references: {
model: 'permissions',
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'RESTRICT',
},
},
{
tableName: 'role_module_bridge',
paranoid: true,
indexes: [
{
unique: true,
fields: ['module_id', 'role_id', 'permission_id'], // All three fields for uniqueness
name: 'role_module_bridge_unique_index',
},
],
}
);

export default RoleModuleBridge;
< /code>
we have modules for every crud operations and which roles will be checked from the database wheter the user is allowed to access the specific module and what what changes the user can do based on the permission
[
{ role_id: 1, module_id: 3, permission_id: 2 },
{ role_id: 1, module_id: 3, permission_id: 3 }
]
< /code>
the above error states below information

[
{ role_id: 1("teacher"), module_id: 3("classes"), permission_id: 2("read") },
{ role_id: 1("teacher"), module_id: 3("classes"), permission_id: 3("update") }
]
< /code>
tried steps
  • i tried Modifying my Sequelize model to use a composite unique constraint on (module_id, role_id, permission_id) but didn't worked at all
  • i tried both bulkCreate() and individual create() calls by using loop but same problem


Подробнее здесь: https://stackoverflow.com/questions/797 ... icate-data
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «MySql»