【问题标题】:How to create an JSON REST API kind of output using SQLite in Flutter?如何在 Flutter 中使用 SQLite 创建 JSON REST API 类型的输出?
【发布时间】:2021-08-31 06:17:27
【问题描述】:

我有两张桌子,

customers表

+----+------------------+
| id | name             |
+----+------------------+
|  1 | Bhagwanti Nair   |
|  2 | Anuja Rana       |
|  3 | Mohana Varrier   |
|  4 | Trilochan Talwar |
|  5 | Charuvrat Gandhi |
+----+------------------+

transactions表

+----+----------+--------+
| id | customer | type   |
+----+----------+--------+
|  1 |        1 | debit  |
|  2 |        3 | debit  |
|  3 |        1 | credit |
|  4 |        4 | debit  |
|  5 |        1 | credit |
|  6 |        5 | credit |
|  7 |        3 | debit  |
|  8 |        4 | credit |
|  9 |        2 | credit |
| 10 |        2 | debit  |
+----+----------+--------+

我正在使用 Sqlflite 数据库构建一个 Flutter 应用程序。我的目标是编写一个查询,当我想获取 customers 时输出以下 JSON 结果:

[
  {
    "id": 1,
    "name": "Bhagwanti Nair",
    "transactions": [
      {
        "id": 1,
        "customer": 1,
        "type": "debit"
      },
      {
        "id": 3,
        "customer": 1,
        "type": "credit"
      },
      {
        "id": 5,
        "customer": 1,
        "type": "credit"
      }
    ]
  },
  ... and so on
]

以同样的方式,我想为transactions 做。就像:

[
  {
    "id": 1,
    "type": "debit",
    "customer": {
      "id": 1,
      "name": "Bhagwanti Nair"
    }
  },
  ... and so on
]

customers 和 transactions 表之间的关系是一对多。

我的问题:

  • 是否可以在 SQLite 数据库中这样做?如果是,请帮助我。
  • 如果不是,解决此问题的最佳方法是什么?

任何帮助将不胜感激。祝你有美好的一天!

【问题讨论】:

    标签: mysql flutter sqlite


    【解决方案1】:

    如果你可以在 Flutter 中使用 SQLite 的 JSON1 Extension,那么你可以使用 json 的聚合函数进行聚合:

    SELECT json_group_array(result) result
    FROM (
      SELECT json_object(
               'id', c.id, 'name', c.name, 
               'transactions',  
               json_group_array(json_object('id', t.id, 'customer', t.customer, 'type', t.type))           
             ) result
      FROM customers c LEFT JOIN transactions t
      ON t.customer = c.id
      GROUP BY c.id
    )
    

    和:

    SELECT json_array(
             json_object(
               'id', t.id, 'type', t.type, 
               'customer',  
               json_group_array(json_object('id', c.id, 'name', c.name))           
             )
           ) result
    FROM transactions t INNER JOIN customers c
    ON c.id = t.customer
    

    请参阅demo。

    【讨论】:

    • 嗨@forpas。有没有办法选择所有字段而不是按名称指定它们?
    • @RavgeetDhillon 不,没有。对于每一列,您必须对其名称进行硬编码。
    猜你喜欢
    • 2018-03-24
    • 2021-02-17
    • 2019-09-17
    • 2015-10-17
    • 1970-01-01
    • 2018-03-19
    • 2018-02-22
    • 2011-07-15
    • 2018-10-03
    相关资源
    最近更新 更多