I have 2 tables "products" and "products_images"., I want to load each product with it's images in the same query and then json_encode then send it to front end.
products table
---- ---------------- -------
| id | product_name | price |
---- ---------------- -------
| 1 | product name 1 | 15 |
---- ---------------- -------
| 2 | product name 2 | 23.25 |
---- ---------------- -------
| 3 | product name 3 | 50 |
---- ---------------- -------
product_images table
---- ------------ -----------------------------------------------------
| id | product_id | image |
---- ------------ -----------------------------------------------------
| 1 | 1 | e5j7eof75y6ey6ke97et5g9thec7e5fnhv54eg9t6gh65bf.png |
---- ------------ -----------------------------------------------------
| 2 | 1 | sefuywe75wjmce5y98nvb7v939ty89e5h45mg5879dghkjh.png |
---- ------------ -----------------------------------------------------
| 3 | 1 | 7u5f9e6jumw75f69w6jc89fwmykdy0tw78if6575m7489tf.png |
---- ------------ -----------------------------------------------------
I want the query to return this
{
id: 5,
product_name: 'product name 1',
price: 25.23,
images: [
{
id: 1,
image: 'e5j7eof75y6ey6ke97et5g9thec7e5fnhv54eg9t6gh65bf.png'
},
{
id: 2,
image: 'sefuywe75wjmce5y98nvb7v939ty89e5h45mg5879dghkjh.png'
},
]
}
What I do is I make a loop on each product in php and then load it's images, but I don't believe this is the best solution or the best performance.
CodePudding user response:
/**
* Results from a SELECT * FROM products query
*/
$products = [
[
'id' => 1,
'product_name' => 'product name 1',
'price' => 15,
],
[
'id' => 2,
'product_name' => 'product name 2',
'price' => 23.25,
],
[
'id' => 3,
'product_name' => 'product name 3',
'price' => 50,
],
];
/**
* Results from either
* SELECT * FROM images
* or
* SELECT * FROM images WHERE product_id IN (?,?,?, ...) <- product ids
*/
$images = [
[
'id' => 1,
'product_id' => 1,
'e5j7eof75y6ey6ke97et5g9thec7e5fnhv54eg9t6gh65bf.png'
],
[
'id' => 2,
'product_id' => 1,
'sefuywe75wjmce5y98nvb7v939ty89e5h45mg5879dghkjh.png'
],
[
'id' => 3,
'product_id' => 1,
'7u5f9e6jumw75f69w6jc89fwmykdy0tw78if6575m7489tf.png'
],
];
foreach ($products as $i => $product) {
$products[$i]['images'] = array_filter($images, function ($image) use ($product) {
return $image['product_id'] === $product['id'];
});
}
var_export($products);
CodePudding user response:
SELECT p.product_id, i.image_png, ...
FROM products AS p
JOIN images AS i ON i.product_id = p.product_id
WHERE ...
ORDER BY ...
Then, in a loop
echo "<img src='...$image_png ...'>";
add an "anchor" if you want the images to be clickable. Add descriptive info if desired.
I see no need for json.
If you are "filtering", it is usually more efficient to build that into the SELECT
statement.