Модель пользователя:
Код: Выделить всё
class User extends Model {
static associate(models) {
User.belongsTo(models.Profile, {
foreignKey: {
name: 'profile_id',
allowNull: true,
},
constraints: false // Disable FK constraint
});
}
}
Код: Выделить всё
class Profile extends Model {
static associate(models) {
Profile.belongsTo(models.User, {
foreignKey: {
name: 'created_by_user_id',
allowNull: false,
},
constraints: true // Keep FK constraint here
});
}
}
Код: Выделить всё
const { QueryInterface } = require('sequelize');
async function syncDatabase() {
await db.sequelize.sync({ alter: true });
// Manually add FK constraint for User -> Profile
const qi = db.sequelize.getQueryInterface();
await qi.addConstraint('users', {
fields: ['profile_id'],
type: 'foreign key',
name: 'user_profile_id_fkey',
references: {
table: 'profiles',
field: 'id'
}
});
}
syncDatabase();
Влияет ли это на поведение ORM Sequelize или на любые скрытые побочные эффекты, когда Sequelize управляет отношениями в памяти?
Влияет ли это на встроенные методы Sequelize (например, user.getProfile(), user.setProfile() ) или производительность быстрой загрузки (
Код: Выделить всё
User.findOne({ include: Profile })Подробнее здесь: https://stackoverflow.com/questions/798 ... lse-with-m
Мобильная версия