Sequelize hasMany失败

时间:2018-07-21 08:18:06

标签: sql orm sequelize.js

我正在尝试与Sequelize建立一对多关联:

这是我的项目:

'use strict';
import { models } from '../sequelize/index';
var ProjectImages = require('./projectImages');

module.exports = (sequelize, DataTypes) => {
    const Projects = sequelize.define(
        'Projects',
        {
            id: {
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                type: DataTypes.INTEGER,
            },

            title: {
                type: DataTypes.STRING,
            },
        },
        {}
    );
    Projects.associate = function(models) {
        // associations can be defined here
        Projects.belongsToMany(models.Tags, { through: models.TagsProjects });
        Projects.hasMany(models.ProjectImages);
    };

    return Projects;
};

这里是项目的图像:

'use strict';
import { models } from '../sequelize/index';

module.exports = (sequelize, DataTypes) => {
    const ProjectImages = sequelize.define(
        'ProjectImages',
        {
            id: {
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                type: DataTypes.INTEGER,
            },

            img: {
                type: DataTypes.STRING,
            },

            createdAt: {
                allowNull: false,
                type: DataTypes.DATE,
                defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
            },

            updatedAt: {
                allowNull: false,
                type: DataTypes.DATE,
                defaultValue: DataTypes.literal('CURRENT_TIMESTAMP'),
            },
        },
        {}
    );

    return ProjectImages;
};

我正在使用类似于this snippet的方式同步数据库。如果我不尝试在ProjectImages中创建任何行,则不会出现任何错误;但是,如果我尝试以此创建行(ID为1的项目存在):

"ProjectImages": [
    {
        "id": 1,
        "img": "https://fakeimg.pl/500x500/",
        "ProjectsId": 1
    }
],

我收到此错误:

Executing (default): INSERT INTO `ProjectImages` 
(`id`,`img`,`createdAt`,`updatedAt`,`ProjectId`) 
VALUES
(1,'https://fakeimg.pl/500x500/',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,1);
[1] Unhandled rejection SequelizeForeignKeyConstraintError: 
Cannot add or update a child row: a foreign key constraint fails 
(`9uhfggfhf2`.`projectimages`, 
CONSTRAINT `projectimages_ibfk_1` 
FOREIGN KEY (`ProjectId`) 
REFERENCES `Projects` (`id`) 
ON DELETE SET NULL 
ON UPDATE CASCADE)

此外,如果我在同步时不向ProjectsImages添加行,也不会出现任何错误,并且如果我尝试通过以下方式在DB中手动插入行:

INSERT INTO `ProjectImages` (`id`,`img`,`createdAt`,`updatedAt`,`ProjectsIdA`) 
VALUES (1,'https://fakeimg.pl/500x500/',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP,1);

它可以正常工作。

有人知道那里发生了什么吗?

1 个答案:

答案 0 :(得分:0)

正如我所说,我正在使用类似于this的东西来与数据库同步。

在代码段的末尾,我必须播种数据:

seed([
    articles, 
    projectImages, 
    projects, 
    tags, 
    tagsProjects, 
    users, 
    usersLogins
]);

您会注意到,我在创建projectImages之前先插入projects。按正确的顺序放置东西可以解决问题。

seed([
    articles, 
    projects, 
    projectImages, 
    tags, 
    tagsProjects, 
    users, 
    usersLogins
]);

:)