使用knex动态创建连接表

use knex to dynamically create join table

本文关键字:连接 创建 动态 knex 使用      更新时间:2023-09-26

我现在正在学习knex,并试图动态地将两个不同表中的id号插入到空表中,该空表稍后将用作连接表。

这是我目前所知道的,但我觉得我现在离基地太远了。

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')
        })
      ]);
    });
};
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有相同数量的项目。

我不知道你为什么要这样做一个中间表,但是到目前为止,我们还不能根据你的信息进行任何连接操作