列违反外键约束

column violate foreign key constraints

我正在尝试在两个表之间创建关系,但是当我尝试将我的对象插入到 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()'));
})

当您创建 tournament table 时,您为列 league_id 指定了 .references('id').inTable('league')。这意味着对于 table 中的每一行,table league 中必须存在一行,其 idleague_id 的值相同前一行的字段。显然在您的插入中(这是您唯一的插入吗?)您正在向 tournament 添加一行,其 league_idleague 中不存在。通常,外部约束(即 .references 部分)意味着您必须首先创建联赛,然后在该联赛中举办锦标赛(这实际上是有道理的)。