开发者社区 问答 正文

将平面查询结果转换为更定义的表结构

我使用烧瓶和mysql为我的一个简单的应用程序创建一个API。我不太确定如何将具有1到多个关系的表上连接的平面查询结果转换为表结构的json对象。 下面是我希望执行的查询示例。每个食谱可能有很多说明和很多成分。

SELECT r.id
  , r.name
  , r.description
  , rd.text
  , ri.name
  , ri.amount
FROM recipes r 
LEFT JOIN recipe_directions rd ON rd.recipe_id = r.id
LEFT JOIN recipe_ingredients ri ON ri.recipe_id = r.id

我希望将这个查询的平面结果转换成json对象,如下所示。mysql连接器或烧瓶中是否已经有一些东西可以用来完成此任务?

[{
  id: 1,
  name: 'Recipe 1',
  description: '...',
  directions: [{
    text: 'Cook the rice'
  },
  {
     text: 'Do the next step...'
  }],
  ingredients: [{
    name: 'Rice',
    amount: '1 cup'
  },
  { 
    name: 'Onion',
    amount: '1'  
  }]
},
{
  id: 2,
  name: 'Recipe 2',
  description: '...',
  directions: [...]
  ingredients: [...]
}]

问题来源StackOverflow 地址:/questions/59385703/convert-flat-query-results-into-a-more-defined-table-structure

展开
收起
kun坤 2019-12-25 22:14:22 358 分享 版权
1 条回答
写回答
取消 提交回答
  • 您要查找的是GROUP_CONCAT()函数。这将允许您在每个返回的行中从连接的表中返回多条记录。你仍然需要做一些格式化,但是这样你就可以将每个食谱作为一个记录返回,其中包含它的方向和成分。 您也可以考虑使用一个类似于records的包,它的.as_dict()函数可以使事情变得更简单。

    2019-12-25 22:14:53
    赞同 展开评论