我使用knex(主页:knexjs.org)从3个表中选择:
无论如何得到这样的结果:
[
{
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 },
]
},
]
我花了很多时间,谢谢
答案 0 :(得分:0)
一种解决方案是将查询分解为多个查询。
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查询,但您需要规范化数据以适合您所需的架构。