【问题标题】:Node.js Knex and mySQL - ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint failsNode.js Knex 和 mySQL - ER_NO_REFERENCED_ROW_2:无法添加或更新子行:外键约束失败
【发布时间】:2020-11-08 21:28:14
【问题描述】:

我正在尝试创建简单的网络应用程序来接收狗收养申请。

我成功运行迁移和种子,并通过这样做创建了这两个表:

问题是当我尝试使用 GUI 创建新应用程序时,出现以下错误:

{“response”:“数据库ForeignKeyViolationError中的错误:插入applicationsdoggo_nameemailnamephone)值('Coco','sam.do@gmail.com ', 'Sam Do', '+12345667') - ER_NO_REFERENCED_ROW_2: 无法添加或更新子行:外键约束失败 (dog_adoption.applications, CONSTRAINT applications_doggo_id_foreign FOREIGN KEY (doggo_id) 参考@ 987654332@(id))"}

这是我试图找出问题所在的第二天。请看我的代码:

迁移文件:


exports.up = function(knex) {

    return knex.schema
        .createTable('doggos', (table) => {
            table.increments('id').notNullable();
            table.string('doggo').notNullable();
            table.integer('age').notNullable();
            table.string('breed').notNullable();
            table.string('picture').notNullable();
        })
        .createTable('applications', (table) => {
            table.increments('id').notNullable();
            table.string('name').notNullable();
            table.string('email').notNullable();
            table.integer('phone').notNullable();
            table.string('doggo_name').notNullable();
            table.integer('doggo_id').unsigned().notNullable();
            table.foreign('doggo_id').references('doggos.id');
            table.dateTime('updated_at').defaultTo(knex.raw('NULL ON UPDATE CURRENT_TIMESTAMP'));
            table.dateTime('created_at').notNullable().defaultTo(knex.raw('CURRENT_TIMESTAMP'));
        });
};

应用种子:

exports.seed = function(knex) {
 
    return knex('doggos').select().then(doggos => {
        return knex('applications').insert([
  
      { name: "xxxxxxxxx", email: "peggy33@gmail.com", phone: 79187877, doggo_name: 'Coco', doggo_id: doggos.find(doggo => doggo.doggo === 'Coco').id},
      { name: "xxxxxxxxxxxxx", email: "watson.dddk@gmail.com", phone: 51393129, doggo_name: 'Tyson', doggo_id: doggos.find(doggo => doggo.doggo === 'Tyson').id},
      { name: "xxxxxxxxxxxxx", email: "ravsp33@gmail.com", phone: 12345678, doggo_name: 'Nicky', doggo_id: doggos.find(doggo => doggo.doggo === 'Nicky').id}
    ]);
});

};

HTML 表格:

      <form action="/apply" method="POST">
         <div class="application-container">
            <label for="name">What is your name?</label>
            <input type="text" placeholder="Your name" name="name" required>   
            <label for="email">E-mail address</label>
            <input type="text" placeholder="e-mail" name="email" required>
            <label for="phone">Phone number</label>
            <input type="text" placeholder="phone" name="phone" required>
            <label for="doggo_name">Name of dog you are interested with</label>
            <input type="text" placeholder="Name of dog you are interested with" name="doggo_name" required>
            <button class="btn btn-primary" type="submit">Submit</button>
            <button class="btn btn-primary" onclick="window.location.href='/'">Cancel</button>
         </div>
      </form>
   </body>

路线:

router.post('/apply', async (req,res) => {
    const { name, email, phone, doggo_name } = req.body;
    console.log(name, email, phone, doggo_name);

    try {
   
        const submittedApplication =  await Application.query().insert({
        name, 
        email,
        phone,
        doggo_name,
        // how to pass doggo_id to the database?

    });
    return res.send({ response: `Succesfully applied for adoption. Please wait patiently for our response!`});
    
    } catch (error) {
    return res.send({ response: "Error in database " + error });
    }
});

如果有人能以全新的眼光看待它并帮助我将数据持久性保存到我的“应用程序”表中,我将不胜感激。

【问题讨论】:

    标签: javascript mysql node.js orm knex.js


    【解决方案1】:

    您将doggo_id 设为不可为空,因此所有现有行的默认值为0,而不是NULL

    但是你也将它设置为doggos.id 的外键。外键约束立即在所有行上失败,因为它们现在都将引用 ID 为 0 的 doggo,这可能不存在。

    您可以通过使其可空来解决该问题(从doggo_id 中删除notNullable()),因为NULL 的意思是“目前不引用任何东西”(而不是“引用ID 为零的doggo”) ),或者通过设置属于实际存在的 doggo 而不是零的 ID 的默认值,如果这在您的用例中有意义的话。

    【讨论】:

    • 您好 CherryDT,非常感谢您的回答。现在我可以将新应用程序保存到数据库中,但是 doggo_id 被保存为 NULL,而不是作为外键来自另一个表的实际 id。你知道我应该如何在我的路由中查询数据库以便保存正确的 id 吗?
    • 我不明白你的意思。您需要从 doggos 表中获取 ID(不知道如何,因为老实说我不完全理解您的结构 - 为什么您有 doggo_name 对另一个的引用doggos 表?)并将其设置为doggo_id。如果是通过名称,那么您必须首先查询doggos 表以从名称中找到 ID,然后在创建新行时使用该 ID。
    猜你喜欢
    • 2016-05-23
    • 2015-07-26
    • 2012-10-09
    • 2015-06-06
    • 2016-08-09
    • 2011-03-31
    • 2013-08-10
    • 1970-01-01
    • 2012-03-14
    相关资源
    最近更新 更多