字段 'foreign key' 没有默认值

Field 'foreign key' doesn't have a default value

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

四分卫:

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;

我尝试插入 Produits table,如下所示:

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" error ocurred { Error: ER_NO_DEFAULT_FOR_FIELD: Field 'Codef' doesn't have a default value 在我的后端。 如您所见,Codef 是我的 table fournisseurs.

上的主键

我该如何解决?

为什么会出现这个错误:

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

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

方案二: 在代码级别添加一些默认值,并在 table 引用外键的地方添加一些默认值。