Node.js Knex 和 mySQL - ER_NO_REFERENCED_ROW_2:无法添加或更新子行:外键约束失败

Node.js Knex and mySQL - ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails

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

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

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

{“响应”:“数据库中的错误 ForeignKeyViolationError:插入 applications (doggo_name, email, name, phone) 值 ( 'Coco'、'sam.do@gmail.com'、'Sam Do'、'+12345667')- ER_NO_REFERENCED_ROW_2:无法添加或更新子行:外键约束失败(dog_adoptionapplications、约束 applications_doggo_id_foreign 外键 (doggo_id) 引用 doggos (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 });
    }
});

如果有人能以全新的眼光看待它并帮助我实现 'applications' table.

的数据持久性,我将不胜感激

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

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

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