列违反了外键约束

时间:2016-09-07 15:45:26

标签: javascript node.js postgresql knex.js

我试图创建两个表之间的关系,但是我似乎得到了,当我尝试将我的对象插入postgres数据库时出现一些问题。我一直收到以下错误:insert or update on table "tournament" violates foreign key constraint "tournament_league_id_foreign"。我猜这与我的knex语法有关吗?

插入数据库

      var data = {
          id: id,
          name: name,
          league_id: leagueId
      };

      var query = knex('tournament').insert(data).toString();
      query += ' on conflict (id) do update set ' + knex.raw('name = ?, updated_at = now()',[name]);

      knex.raw(query).catch(function(error) {
        log.error(error);
      })

Knex表格

knex.schema.createTable('league', function(table) {
    table.increments('id').primary();
    table.string('slug').unique();
    table.string('name');
    table.timestamp('created_at').notNullable().defaultTo(knex.raw('now()'));
    table.timestamp('updated_at').notNullable().defaultTo(knex.raw('now()'));
}),
knex.schema.createTable('tournament', function(table) {
    table.string('id').primary();
    table.integer('league_id').unsigned().references('id').inTable('league');
    table.string('name');
    table.boolean('resolved');
    table.timestamp('created_at').notNullable().defaultTo(knex.raw('now()'));
    table.timestamp('updated_at').notNullable().defaultTo(knex.raw('now()'));
})

1 个答案:

答案 0 :(得分:3)

当您为tournament列创建league_id表时,您指定了.references('id').inTable('league')。这意味着对于该表中的每一行,表league中必须存在一行,其id与前一行中league_id字段的值相同。显然在您的插入中(这是您唯一的插入吗?),您要向tournament添加一行,league_idleague中不存在.references。作为一项规则,外国约束(即Filesystem Usage: ============================== Use% Mounted 32% /lustre/work1 56% /lustre/work2 Inode Usage ============================== IUse% Mounted 20% /lustre/work1 70% /lustre/work2 部分)意味着你必须首先创建联盟,然后在该联盟中创造锦标赛(这实际上是有意义的)。