猿问

MySQL选择多维?

我想从我的数据库中选择所有帖子及其附件。


这是带有虚拟数据的结构:


帖子表


id       | post          | userId   | 

---------|---------------|----------|

1        | "hello"       |  1       |

2        | "world"       |  1       |

3        | "ouch"        |  2       |

4        | "test"        |  1       |

附件表


id       | postId        | fileName |  time    | 

---------|---------------|----------|----------|

1        | 1             |"hey.jpg" |        0 |

2        | 1             |"test.png"| 53252354 |

3        | 2             |"asd.png" |        0 |

4        | 4             |"asd2.png"|        0 |

到目前为止,我的代码看起来像这样,但我并没有真正得到我想要的。


$qry = $db->prepare('

SELECT p.id

     , p.post

     , p.userId

     , att.fileName

     , att.time

  FROM posts p

  LEFT 

  JOIN attachments att 

    ON att.postId = p.id

');

$qry->execute();

$postsArray = $qry->fetchAll(PDO::FETCH_ASSOC);

我想要这样的东西:


[{'id': 1,

'post': 'hello',

'userId': 1,

'attachments': [{'fileName': 'hey.jpg', 'time:' 0}, ... ]

}, ... ]

我怎么能做到这一点?


宝慕林4294392
浏览 164回答 2
2回答

函数式编程

您的查询将为您提供所需结果的正确数据,您可以在 PHP 中进行后处理以获得所需的格式:foreach ($postArray as $post) {    $fixed_part = array('id' => $post['id'], 'post' => $post['post'], 'userId' => $post['userId']);    $key = serialize($fixed_part);    if (!isset($out[$key])) $out[$key] = $fixed_part;    $out[$key]['attachments'][] = array('fileName' => $post['fileName'], 'time' => $post['time']);}$out = array_values($out);echo json_encode($out, JSON_PRETTY_PRINT);输出太长无法发布,但可以在此演示中看到。查询结果可以在dbfiddle上看到。
随时随地看视频慕课网APP
我要回答