简体   繁体   English

MySql-字段“ park_id”没有默认值

[英]MySql - Field 'park_id' doesn't have a default value

I am very new to Mysql, and I have been stuck on this for a while. 我是Mysql的新手,并且我对此坚持了一段时间。

I am using bookshelfjs to create a many-to-many relatioship,everytime I try to attach my articles to parks I get the following error. 我正在使用bookshelfjs创建多对多关系,每次尝试将文章附加到公园时,都会出现以下错误。

(node:24480) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: insert into articles_parks ( article_id , park_id ) values (0, DEFAULT) - ER_NO_DEFAULT_FOR_FIELD: Field 'park_id' doesn't have a default value (节点:24480)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):错误:插入articles_parksarticle_idpark_id )值(0,DEFAULT)-ER_NO_DEFAULT_FOR_FIELD:字段'park_id'没有默认值

this is my MySQL code: 这是我的MySQL代码:

Create table parks( 
   park_id integer,
   primary key (park_id)
);

Create table articles(
   article_id integer,
   primary key (article_id)
);

CREATE TABLE articles_parks(
   article_id integer,
   park_id    integer,
   Primary Key (article_id,park_id), 
   Foreign Key (article_id) REFERENCES articles(article_id),
   Foreign Key (park_id) REFERENCES parks(park_id)
);

this is my bookshelf code: 这是我的书架代码:

var bookshelf = require('bookshelf')(knex);

    var Article = bookshelf.Model.extend({
      tableName: 'articles',
      park: function() {
        return this.belongsToMany(Park);
      }
    });

    var Park = bookshelf.Model.extend({
      tableName: 'parks',
      articles: function() {
        return this.belongsToMany(Article);
      }
    });
    const number = 197;
    var article1 = new Article({article_id: number});

    Promise.all([article1.save()])
      .then(function() {
        return Promise.all([
        new Park({park_id: 200}).articles().attach([article1]),
      ]);
    })

Your two primary keys (park_id and article_id) are not set to be auto incremented. 您的两个主键(park_id和article_id)未设置为自动递增。 In MySQL, you must explicitly state that you want the primary keys to be auto incremented or it will assume you are going to manually assign them values. 在MySQL中,您必须明确声明要自动递增主键,否则将假定您将要手动为其分配值。 This is why it is returning an error that they are missing a default value. 这就是为什么它返回错误的原因,因为它们缺少默认值。

Try editing your SQL code to this: 尝试将您的SQL代码编辑为此:

Create table parks( 
   park_id integer AUTO_INCREMENT,
   primary key (park_id)
);

Create table articles(
   article_id integer AUTO_INCREMENT,
   primary key (article_id)
);

CREATE TABLE articles_parks(
   article_id integer,
   park_id    integer,
   Primary Key (article_id,park_id), 
   Foreign Key (article_id) REFERENCES articles(article_id),
   Foreign Key (park_id) REFERENCES parks(park_id)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM