dongqiao3214 2017-04-27 12:12
浏览 69
已采纳

查询以显示包含所有附加缩略图的帖子

Problem: I need to display a list of posts, each with their attached thumbnails. Thumbnails are in the filesystem, I just need the path that was stored in the mysql db. Si I have 2 db tables: one for posts and one for images_attachments.

I'm not sure what is the appropriate format I should retrieve from the db to achieve what I need. Right now I have this:

SELECT posts.id, posts.post_title, images_attachments.image_name
FROM posts 
INNER JOIN images_attachments ON posts.id = image_post_post_id

This produce rows with post_id, post_title and the corresponding joined images_attachments.image_name which is the path.

Is this how I should do it ? Problem is that I get as much rows per post as it has images. This will involve more logic on the template to show the post title, and under it all the thumbs.

Second problem is that it will ignore posts with no attached thumbnails.

Please advise if i'm in the wrong direction, and if it is the case, how to format the query.

(this is NOT wordpress, just raw mysql and php templates)

  • 写回答

1条回答 默认 最新

  • doulao3905 2017-04-27 12:18
    关注

    You have many-to-one (many attachments to one post), therefore you are probably better just doing a normal select, looping through the rows, and querying for attachments.

    <?php
    
    foreach ($posts as $post) {
        $attachments = // query other table
        foreach($attachments as $attachment) {
            // do stuff with attachment
        }
    }
    

    The way you are doing it, you would need to create dynamic additional columns based on the number of attachments, and that's a headache. This also ensures your posts with no attachments will also be fetched.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测