5
我從一個數組,看起來像這樣我的播種完成分貝(詞彙和定義在一個多對多的關係):Knex遷移播種與外鍵錯誤
var seeds = [
{
"word": "Click",
"definitions": ["Computer", "Mouse", "Tasto", "Pulsante", "Selezionare"]
}, {
"word": "Galoppo",
"definitions": ["Cavallo", "Andatura", "Trotto", "Ippica", "Passo"]
}, {
"word": "Raggio",
"definitions": ["Sole", "Bicicletta", "Diametro", "Luce", "Laser"]
}, {
.
.
.goes on for 1089 objects
這是我的嘗試:
exports.seed = function (knex, Promise) {
var promises = seeds.map(function (seed) {
return knex('words').insert({
word: seed.word
}, 'id').then(function (word_id) {
var promises = seed.definitions.map(function (definition) {
return knex('definitions').insert({
definition: definition
}, 'id').catch(function (err) {
if (err.code === 1062)
return knex('definitions').select('id').where({
definition: definition
}).then(function (duplicate) {
return knex('definitions_words').insert({
definition_id: duplicate[0].id,
word_id: word_id
});
});
}).then(function (definition_id) {
return knex('definitions_words').insert({
definition_id: definition_id,
word_id: word_id
});
});
});
return Promise.all(promises);
});
});
return Promise.all(promises);
};
詞在我的種子獨一無二的,但定義可能會重複,所以我抓住了重複錯誤,並抓住重複的ID提出,在路口表。它似乎做工精細,實際上結合表結束了1089×5行(5445),但我得到的CLI的錯誤:
Error: Cannot add or update a child row: a foreign key constraint fails
(`mytable`.`definitions_words`,
CONSTRAINT `definitions_words_definition_id_foreign`
FOREIGN KEY (`definition_id`) REFERENCES `definitions` (`id`))