mysql - 字段 'foreign key' 没有默认值

标签 mysql node.js express foreign-keys create-table

我使用nodeJS和MySQL开发了我的后端,我有如下三个表:

四人组:

CREATE TABLE fournisseurs (

 Codef bigint(21) NOT NULL ,
 Noment varchar(20) COLLATE utf8_unicode_ci NOT NULL,
 Prenomf varchar(20) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (Codef, Prenomf)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

类别:

CREATE TABLE categorie (

 Idcat  bigint(21) NOT NULL AUTO_INCREMENT,
 Nomcat varchar(20) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (Idcat, Nomcat)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

产品:

CREATE TABLE produits (

 Codep bigint(21) NOT NULL AUTO_INCREMENT,
 Reference bigint(21) NOT NULL,
 Nomp varchar(20) COLLATE utf8_unicode_ci NOT NULL ,
 Codef bigint(21) NOT NULL  ,
 Prenomf varchar(20) COLLATE utf8_unicode_ci NOT NULL,
 Idcat  bigint(21) NOT NULL  ,
 Nomcat varchar(20) COLLATE utf8_unicode_ci NOT NULL,
 Description varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (Codep ),
 FOREIGN KEY (Codef, Prenomf) REFERENCES fournisseurs (Codef, Prenomf)
  ON DELETE CASCADE
 ON UPDATE CASCADE ,
 FOREIGN KEY (Idcat, Nomcat) REFERENCES categorie (Idcat, Nomcat)
 ON DELETE CASCADE
 ON UPDATE CASCADE 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10;

我尝试插入到产品表中,如下所示:

exports.ajouterprod = function(req, res) {
    console.log("req", req.body);
    var today = new Date();
    var produits = {
        "Reference": req.body.Reference,
        "Nomp": req.body.Nomp,
        // "Codef": req.body.Codef,
        "Prenomf": req.body.Prenomf,
        //"Idcat": req.body.Idcat,
        "Nomcat": req.body.Nomcat,
        "Description": req.body.Description
    }
    connection.query('INSERT INTO produits SET ?', produits, function(error, results, fields) {
        if (error) {
            console.log("error ocurred", error);
            res.send({
                "code": 400,
                "failed": "error ocurred"
            })
        }
        else {

            res.send({
                "code": 200,
                "success": "produit registered sucessfully"
            });
        }

    })
};

当我用 Postman 运行它时,我得到:"failed": "error ocurred" 并且发生错误{错误:ER_NO_DEFAULT_FOR_FIELD:字段“Codef”在我的后端没有默认值。 如您所见,Codef 是我的表 fournisseurs 上的主键。

我该如何解决这个问题?

最佳答案

为什么会出现这个错误:

由于您向 Produits 插入数据并且未指定任何值 Codef,因此会生成此错误,因为外键需要一个值(也可以为 null)

解决方案1: 更改 Produits 的表结构,使其具有一些默认值,该默认值要么存在于另一个表(引用外键的地方)中,要么为空值。

解决方案 2: 在代码级别添加一些默认值,并在引用外键的表中添加相同的默认值。

关于mysql - 字段 'foreign key' 没有默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566793/

相关文章:

php - 登录脚本-尽管输入正确,用户名和密码始终为false

mysql - 根据当前时间创建 View (MySql)

javascript - 我可以并行运行多少个 NodeJS Express 服务器?

javascript - 从不解析从 Node+Express API 到 MongoDB 的 HTTP 请求

mysql - 查询以查找共享相同帐号的用户

mysql - SQL查询多个总和和总和的平均值

javascript - 链接的 npm 库未在本地更新

javascript - Sails.js 与 React.js,如何正确做?

javascript - 服务器本身捕获的套接字 io 发出

express - Passport 本地临时密码(首次登录时更改)