提问者:小点点

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


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

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

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

{“响应”:“数据库ForeignKeyViolationError中出错:插入Applications(Doggo_NameEmailNamePhone)值('coco','sam.do@gmail.com','sam Do','+12345667')-ER_NO_REFERENCED_ROW2:无法添加或更新子行:外键约束失败(DOG_ADOAD

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

迁移文件:


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: "Peggy Brown", email: "peggy33@gmail.com", phone: 79187877, doggo_name: 'Coco', doggo_id: doggos.find(doggo => doggo.doggo === 'Coco').id},
      { name: "Anna Watson", email: "watson.dddk@gmail.com", phone: 51393129, doggo_name: 'Tyson', doggo_id: doggos.find(doggo => doggo.doggo === 'Tyson').id},
      { name: "Radek Pyzel", 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

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

如果有人能用新的眼光看待它,并帮助我实现“应用程序”表的数据持久化,我将非常感激。


共1个答案

匿名用户

您使doggo_id不可为空,因此它将获得0作为所有现有行的默认值,而不是null

但是您还将它设置为doggos.id的外键。 foreign key约束在所有行上立即失败,因为它们现在都引用ID0的doggo,而这个ID0可能并不存在。

您可以通过使其为空(从doggo_id中删除notnullable())来解决这个问题,这是因为null意味着“此刻不引用任何东西”(与“引用ID为零的doggo”相反),或者通过设置一个属于实际存在的doggo而不是零的ID的默认值来解决这个问题,如果这在您的用例中有意义的话。