Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove left join in function Knex.JS?

How to remove left join integration?

await knex.select().from("dishes")
            .leftJoin("companies", function () {
                if (companyId) {
                    this.on("dishes.companyId", "=", "companies.id")
                } else {
                    // I want to remove left join if companyId is false
                    return false;
                }
            })

I’m got an error:

code: 'ER_PARSE_ERROR',
  sql: 'select * from `dishes` left join `companies`'
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s unclear which part you’re having difficulty with. Your current error is caused by the fact that you are trying to create a left join without giving it a condition to join on.

I suggest you move your if (companyId) check outside the leftJoin() call so that two separate queries are created.

async function getDishes(companyId) {
   if (companyId) {
      return knex.select().from("dishes").
          leftJoin("companies", "dishes.companyId", "companies.id");
   }
   return knex.select().from("dishes");
}

Which could potentially be simplified to

async function getDishes(companyId) {
   const dishes = knex.select().from("dishes");
   return companyId 
       ? dishes.leftJoin("companies", "dishes.companyId", "companies.id");
       : dishes;
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading