Amir
Amir

Reputation: 69

knex dynamic join table

This is the statement for select single table and table name is passed dynamically, where db is knex.

db.schema.hasTable(tblName).then((exists) => {
      if (exists) {
        db(tblName).select().then((data)=>{
            res.json({success: true,data:data});
        }).catch((err)=>{
            console.log(err);
            res.status(401).json({success: false,msg:"Record not found"});
        });;
      }
      else {
        res.status(401).json({success: false,msg:"Invalid Table "+tblName});
      }
    });

Is there any way I can do multiple join dynamically? Instead of table name parameter I need to pass table list array which contains the required info for join.

Thanks in advance

const tableArray = [
        {order: 1, table_name:"contatcs", is_join:false, join_table:"", join="", multi_join_by:false, join_by_condition="", s_column="", d_column="", join_by_params = "", },
        {order: 2, table_name:"address", is_join:true, join_table:"address", join="inner", multi_join_by:false, join_by_condition="", s_column="contactId", d_column="contactId", join_by_params = "=", },
        {order: 3, table_name:"people", is_join:true, join_table:"address", join="inner", multi_join_by:false, join_by_condition="", s_column="contactId", d_column="contactId", join_by_params = "=", }
    ];

Upvotes: 0

Views: 1041

Answers (1)

felixmosh
felixmosh

Reputation: 35493

Since knex is a query builder, it invokes the query only when the then is called.

So you can do something like:

const query = db(tblName).select();

tableArray.forEach((join) => {
  if (join.join === "inner") {
    query.innerJoin(join.table_name);
    // continue with the build
  } else {
    query.join(join.table_mame)
    // continue with the build
  }
});

query.then((data) => {
  res.json({ success: true, data: data });
});

Upvotes: 1

Related Questions