So I am trying to get a single item data like itemID, itemSKU etc. from multiple tables. And display in the view. The example item I provided down below has three images attached.If I use return $query->row_array(); I will get only one row returned. If I use $query->result_array(), I will get three rows returned. For single item page, I don't want to use foreach to display the result.
My Model
$this->db->join('itemsToCats', 'items.itemID = itemsToCats.itemId','left');
$this->db->join('categories', 'itemsToCats.catId = categories.ctgID', 'left');
$this->db->join('itemImg', ' items.itemID = itemImg.itemID', 'left');
$this->db->select('items.itemID, itemSKU, itemName, itemSDesc, addDate, chgDate, ctgID, ctgName, parentID, itemImg');
$query = $this->db->get_where('items', array('items.itemID' => $itemID));
return $query->row_array();
Output
Array
(
[itemID] => 521
[itemSKU] => image part number
[itemName] => multiple images
[itemSDesc] =>
[addDate] => 2018-07-12 16:17:09
[chgDate] => 0000-00-00 00:00:00
[ctgID] => 67
[ctgName] => Pipe Bending
[parentID] => 46
[itemImg] => 234-gy_hello1.png
)
If I use return $query->result_array() I get this:
Array
(
[0] => Array
(
[itemID] => 521
[itemSKU] => image part number
[itemName] => multiple images
[itemSDesc] =>
[addDate] => 2018-07-12 16:17:09
[chgDate] => 0000-00-00 00:00:00
[ctgID] => 67
[ctgName] => Pipe Bending
[parentID] => 46
[itemImg] => 234-gy_hello1.png
)
[1] => Array
(
[itemID] => 521
[itemSKU] => image part number
[itemName] => multiple images
[itemSDesc] =>
[addDate] => 2018-07-12 16:17:09
[chgDate] => 0000-00-00 00:00:00
[ctgID] => 67
[ctgName] => Pipe Bending
[parentID] => 46
[itemImg] => cac1f0ad0720ac05e76fd990de2d309e.png
)
[2] => Array
(
[itemID] => 521
[itemSKU] => image part number
[itemName] => multiple images
[itemSDesc] =>
[addDate] => 2018-07-12 16:17:09
[chgDate] => 0000-00-00 00:00:00
[ctgID] => 67
[ctgName] => Pipe Bending
[parentID] => 46
[itemImg] => eee779a15e340e2a0f4d0b682e900862.png
)
)
What I want is this:
Array
(
[itemID] => 521
[itemSKU] => image part number
[itemName] => multiple images
[itemSDesc] =>
[addDate] => 2018-07-12 16:17:09
[chgDate] => 0000-00-00 00:00:00
[ctgID] => 67
[ctgName] => Pipe Bending
[parentID] => 46
[itemImg] => Array
(
[0] => 234-gy_hello1.png
[1] => cac1f0ad0720ac05e76fd990de2d309e.png
[2] => eee779a15e340e2a0f4d0b682e900862.png
)
)
Is there some SQL trick I can use to achieve the data structure, or I need to modify the result data in the model? Thank you!
GROUP BY itemID
and selectGROUP_CONCAT(itemImg SEPARATOR '<somecharacter>')
and thenexplode()
the itemImg value in the result set. – zenzelezz