Reputation: 5001
There are three tables in my application: products
, sizes
and product_sizes
.
The structure is something like this:
products' table:
id INT(11)
name VARCHAR(48)
sizes' table:
id INT(11)
name VARCHAR(48)
product_sizes' table:
id INT(11)
product_id INT(11)
size_id INT(11)
As you can see, there are some products that has three sizes for instance. What I need to show up to the user those three sizes with their names.
What I have in PHP now:
index.php (view)
<?php
[...]
foreach ($products as $product) {
echo $product->name; // for each item, show its name
}
And I want to iterate with the sizes just like that:
<?php
[...]
foreach ($products as $product) {
[...]
echo $product->name;
foreach($product->sizes as $size) {
echo $size; // for each item, shows its available sizes (s, M, L, for example)
}
}
How can I make sizes work together to the products in a consistent way like showed above?
My query, for now is:
SELECT products.id, products.name, sizes.name FROM products
JOIN product_sizes ON product_sizes.product_id = products.id
JOIN sizes ON product_sizes.size_id = sizes.id
I marked as CodeIgniter because if there have a way to solve this problem through its ACtiveRecord, no problem because my application runs on the top of CI. You can share your solution normally.
Upvotes: 1
Views: 1845
Reputation: 15912
What you want to do you may achieve it with a bit of SQL, check this, it's an example of getting grouped values (what you want to do) into a single field:
http://sqlfiddle.com/#!2/400994/20
In your case, you'd do something like:
SELECT
p.id
, p.name
, CONCAT( "[", GROUP_CONCAT( s.name SEPARATOR ", "), "]" ) sizes
FROM products p
INNER JOIN product_sizes ps
ON ps.product_id = p.id
INNER JOIN sizes s
ON ps.size_id = s.id
GROUP BY p.id
In your PHP, with a json_decode, you'd get the values you wanted.
foreach ($products as $product) {
[...]
echo $product->name;
$product_sizes = json_decode($product->sizes);
foreach($product_sizes as $size) {
echo $size; // for each item, shows its available sizes (s, M, L, for example)
}
}
The advantage of a JSON string, is that when you format it you may get complicated structure data with it.
Upvotes: 0
Reputation: 4414
You can use GROUP_CONCAT() in your SQL Query to concat multiple sizes in a one column and later process that cell value.
SELECT products.id, products.name, GROUP_CONCAT( sizes.name ) available_sizes
FROM products
JOIN product_sizes ON product_sizes.product_id = products.id
JOIN sizes ON product_sizes.size_id = sizes.id
group by products.id
in PHP you can use it as following.
foreach ($products as $product) {
[...]
echo $product->name;
$available_sizes=explode(",",$product->available_sizes);
foreach($available_sizes as $size) {
echo $size; // for each item, shows its available sizes (s, M, L, for example)
}
}
Hope, this helps :)
Upvotes: 7