2016-09-09 22 views
1

私は今knexを学んでおり、2つの異なるテーブルのID番号を後で結合テーブルとして使用される空のテーブルに動的に挿入しようとしています。knexを使用して結合テーブルを動的に作成

これは私がこれまで行ってきたことですが、私は現時点では基本的に離れていると感じています。

exports.seed = function(knex, Promise) { 
    return knex('future_join_table').del() 
     .then(function() { 
     return Promise.all([ 
     // Inserts seed entries 
     knex('future_join_table').insert({ 
      first_id: knex('table1').select('id'), 
      second_id: knex('table2').select('id') 
     }) 
     ]); 
    }); 
}; 

答えて

0
exports.seed = (knex) => { 
    let table1Array = []; 
    const toBeInsertRows = [] 
    return knex('future_join_table').del() 
    .then(() => knex.select('id').from('table1')) 
    .then((rows) => { 
    table1Array = rows; 
    return knex.select('id').from('table2') 
    }) 
    .then((rows) => { 
    rows.forEach((row, index) => toBeInsertRows.push({ first_id: table1Array[index].id, second_id: row.id })) 
    return knex('future_join_table').insert(toBeInsertRows); 
    }); 
} 

上記のコードは、あなたのtable1table2は、アイテムの数が同じと仮定します。

私はこのようにミドルテーブルを作成する理由はわかりませんが、これまでのところ、あなたの情報にどのジョイン操作ベースも実行できません。

関連する問題