如何使用knex构建此查询

时间:2018-02-01 17:41:18

标签: knex.js

我使用knex(主页:knexjs.org)从3个表中选择:

  • 用户(身份,姓名,年龄)
  • user_food(user_id,food_id,quantity)
  • 食物(身份证,姓名)

无论如何得到这样的结果:

[
   {
        user_id: 1,
        name: "john",
        foods: [
            {food_id: 1, name: "pizza", quantity: 2 },
            {food_id: 2, name: "some other food", quantity: 1 },
        ]
   },
   {
        user_id: 2,
        name: "ellen",
        foods: [
            {food_id: 3, name: "humberger", quantity: 1 },
            {food_id: 4, name: "some other food", quantity: 2 },
        ]
   },
]

我花了很多时间,谢谢

1 个答案:

答案 0 :(得分:0)

一种解决方案是将查询分解为多个查询。

  1. 查找所有用户
  2. 为每个用户找到他们的食物
  3. const userFoods = userId =>
      knex('food').select({ foodId: 'food.id' }, 'name', 'user_food.quantity')
      .innerJoin('user_food', 'food.id', 'user_food.food_id')
      .where('user_food.user_id', userId);
    
    const userWithFoods = user =>
      userFoods(user.userId)
      .then(foods => ({ ...user, foods })));
    
    const users = () =>
      knex('user').select({ userId: 'id' }, 'name')
      .then(users => Promise.all(users.map(userWithFoods)));
    

    可以将其写为单个knex查询,但您需要规范化数据以适合您所需的架构。