2017-05-27 111 views
0

當我嘗試在Knex和Postgres中運行種子時,我仍然得到相同的錯誤。錯誤是error: insert or update on table "locations" violates foreign key constraint "locations_user_id_fore ign"。任何人都可以弄清楚爲什麼它會拋出這個錯誤?我試過改變一堆東西。謝謝!Postgres/Knex「在表格上插入或更新」位置「違反了外鍵約束」

用戶遷移

exports.up = function(knex, Promise) { 
    return knex.schema.createTable('users', function(table) { 
    table.increments() 
    table.string('email').notNullable(); 
    table.string('password').notNullable(); 
    }) 
}; 

exports.down = function(knex, Promise) { 
    return knex.schema.dropTable('users') 
}; 

位置表

exports.up = function(knex, Promise) { 
    return knex.schema.createTable('locations', function(table) { 
    table.increments('id'); 
    table.string('placename').notNullable(); 
    table.float('latitude').notNullable(); 
    table.float('longitude').notNullable(); 
    table.integer('user_id').notNullable().references('id').inTable('users').onDelete('cascade'); 
    }) 
}; 

exports.down = function(knex, Promise) { 
    return knex.schema.dropTable('locations') 
}; 

用戶種子

exports.seed = function(knex, Promise) { 
    // Deletes ALL existing entries 
    return knex('users').del() 
    .then(function() { 
     // Inserts seed entries 
     return knex('users').insert([ 
     {email: '[email protected]', password: 'p1'}, 
     {email: '[email protected]', password: 'p2'}, 
     {email: '[email protected]', password: 'p3'} 
     ]); 
    }); 
}; 

位置種子

exports.seed = function(knex, Promise) { 
    // Deletes ALL existing entries 
    return knex('locations').del() 
    .then(function() { 
     // Inserts seed entries 
     return knex('locations').insert([ 
     {placename: 'Himeji', latitude: 34.8394, longitude: 134.6939, user_id: 1}, 
     {placename: 'Long Beach', latitude: 33.7701, longitude: 118.1937, user_id: 3}, 
     {placename: 'Seattle', latitude: 47.6253, longitude: 122.3222, user_id: 2} 
     ]); 
    }); 
}; 

回答

3

作爲回答,因爲它太大而不能發表評論。

那麼錯誤信息已經足夠清晰,您違反了foreign key約束條件。

這是因爲在locations插入一行你需要給一個user_id爲好,這是引用到id列在表users。如果該特定用戶不在users表中,則不能在該位置插入該user_id。看到這一行

table.integer('user_id').notNullable().references('id').inTable('users').onDelete('cascade'); 

所以首先你要添加userusers表,那麼你可以將它插入它location

+0

謝謝,是的,我意識到我的種子運行不規範。所以我試圖用引用用戶的外鍵創建位置,之後我甚至創建了用戶。謝謝! – lnamba

相關問題