如何洗掉左連接集成?
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;
}
})
我有一個錯誤:
code: 'ER_PARSE_ERROR',
sql: 'select * from `dishes` left join `companies`'
}
uj5u.com熱心網友回復:
目前尚不清楚您在哪個部分遇到困難。您當前的錯誤是由于您嘗試創建左連接而不給它加入條件的事實引起的。
我建議您將if (companyId)支票移到leftJoin()通話之外,以便創建兩個單獨的查詢。
async function getDishes(companyId) {
if (companyId) {
return knex.select().from("dishes").
leftJoin("companies", "dishes.companyId", "companies.id");
}
return knex.select().from("dishes");
}
這可能會簡化為
async function getDishes(companyId) {
const dishes = knex.select().from("dishes");
return companyId
? dishes.leftJoin("companies", "dishes.companyId", "companies.id");
: dishes;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464637.html
