简体   繁体   English

PHP MySQL:如何从图像表中检索与商品ID相关的所有图像

[英]PHP MySQL: How to retrieve all images associated to an item id from images table

So I have two tables. 所以我有两个桌子。

Items table: 项目表:

+---------+-----------+
| item_id | item_name |
+---------+-----------+
|       1 | Item One  |
|       2 | Item Two  |
+---------+-----------+

Images table: 图片表:

+---------+----------------------+
| item_id |      item_image      |
+---------+----------------------+
|       1 | clofr9ohuvex5cxeyrfm |
|       1 | slnorjbqfd2x7ks0marp |
|       1 | oomkjtomvasklx9be4sq |
|       2 | um8donrpeuvfrmqb7qt  |
|       2 | lowcvoaijxniiqdj5eoe |
|       2 | qwxfartcsdyusw4lrngi |
+---------+----------------------+

My php code to get list of items with their associative images: 我的php代码可获取带有相关图像的项目列表:

$itemsQuery = $db->prepare("
        SELECT *
        FROM items a,item_images b
        WHERE a.item_id = b.item_id
    ");
    $itemsQuery->execute();
    $items = $itemsQuery->fetchAll(PDO::FETCH_ASSOC);

    var_dump($items);

I am getting 6 results instead of 2. 我得到6个结果,而不是2个。

What I want is to show the 2 items present in the "items table" with their associative images from the "images table" based on the item_id. 我想要显示的是“ items table”中存在的2个项目以及基于item_id的“ images table”中的相关图像。

I can query the "items table" and loop through it to query the database one more time to get the images. 我可以查询“ items table”并遍历整个表以查询数据库一次以获取图像。 But how can I do it in one database call? 但是如何在一个数据库调用中做到这一点?

You can use GROUP_CONCAT to get MySQL to group all the values from the second table to a single column for you: 您可以使用GROUP_CONCAT来获取MySQL,以便将第二个表中的所有值分组到一个列中:

SELECT 
    a.*, GROUP_CONCAT(b.item_image) AS item_images
FROM
    items a,item_images b
WHERE
    a.item_id = b.item_id
GROUP BY
    a.item_id

The result will be a key named item_images that contain each item_image for that item , separated by , : 其结果将是一个名为关键item_images包含每个item_imageitem ,通过分离,

um8donrpeuvfrmqb7qt,lowcvoaijxniiqdj5eoe,qwxfartcsdyusw4lrngi

You can then use explode on the PHP side if you want it as an array instead. 然后,如果您希望将其作为数组使用,则可以在PHP端使用explode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM