简体   繁体   中英

KnexJS with multiple tables and aliases

I've been playing with KnexJS lately and I've got most of what I need from KnexJS documentation, however I have a bit more complex MySQL query that I can't 'port' on my own to Knex. I know there's an option to use .raw() , however I'd like to avoid that if possible.

My working MySQL query looks like this:

SELECT A.profile_id, C.model_name, D.brand_name, A.car_plate
FROM carsdb.profiles_has_cars A,
     carsdb.profiles B,
     carsdb.brands_cars C,
     carsdb.brands D
WHERE A.profile_id = B.user_id AND
      A.car_id = C.id AND
      A.brand_id = D.id;

What I got so far is:

  return new Promise((resolve, reject) => {
    db({
      A: "profiles_has_cars",
      B: "profiles",
      C: "brands_cars",
      D: "brands"
    })
      .select("A.profile_id", "C.model_name", "D.brand_name", "A.car_plate")
      .where({
        "A.profile_id": userId,
        "A.car_id": "C.id",
        "A.brand_id": "D.id"
      })
      .then(results => {
        if (results > 0) {
          resolve(results);
        } else {
          reject("There is a problem with a query");
        }
      });
  });

I've also tried using an object as an argument in .where() , but that didn't do anything either.

Any help or suggestion?

Oh, I've got it. knex doesn't understand that .where values are actually references to another fields and interpret them as strings.

Try to replace such with one more for each .whereRaw("A.car_id = C.id") . (For references only, not for actual values).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM