我写了这个查询:
SELECT p.category, r.id, r.code, u.hash_name, r.created_at, r.updated_at FROM uploads AS u
JOIN refrigerators AS r ON u.id=r.image
JOIN products_refrigerators AS pr ON pr.refrigerator_id=r.id
JOIN products p ON pr.product_id = p.id
这就是结果:
Array
(
[0] => stdClass Object
(
[category] => lamps
[id] => 1
[code] => canopy
[path] => public/uploads/AAmAnnC2Yoij9QblcybTJefE5vTQrNZsfDCWqOPt.jpeg
[created_at] => 2018-02-21 11:15:06
[updated_at] => 2018-02-21 11:15:06
)
[1] => stdClass Object
(
[category] => panels
[id] => 1
[code] => canopy
[path] => public/uploads/AAmAnnC2Yoij9QblcybTJefE5vTQrNZsfDCWqOPt.jpeg
[created_at] => 2018-02-21 11:15:06
[updated_at] => 2018-02-21 11:15:06
)
[2] => stdClass Object
(
[category] => lamps
[id] => 2
[code] => canopy2
[path] => public/uploads/nqDT4gEXbF0opPmEpa1cPo5iPSulRoesYcgHiOA3.jpeg
[created_at] => 2018-02-21 11:17:44
[updated_at] => 2018-02-21 11:17:44
)
[3] => stdClass Object
(
[category] => lamps
[id] => 3
[code] => QWE
[path] => public/uploads/0TSrz6j3JJH17XgEs2161mOh8aYgDikujdYwrCWR.jpeg
[created_at] => 2018-02-21 11:18:13
[updated_at] => 2018-02-21 11:18:13
)
[4] => stdClass Object
(
[category] => panels
[id] => 3
[code] => QWE
[path] => public/uploads/0TSrz6j3JJH17XgEs2161mOh8aYgDikujdYwrCWR.jpeg
[created_at] => 2018-02-21 11:18:13
[updated_at] => 2018-02-21 11:18:13
)
)
我的问题是:有没有办法得到这样的结果(=将category
属性转换为一个数组,如果存在多个相关类别,则对其进行分组)
Array
(
[0] => stdClass Object
(
[category] => Array
(
[0] => lamps
[1] => panels
)
[id] => 1
[code] => canopy
[path] => public/uploads/AAmAnnC2Yoij9QblcybTJefE5vTQrNZsfDCWqOPt.jpeg
[created_at] => 2018-02-21 11:15:06
[updated_at] => 2018-02-21 11:15:06
)
[1] => stdClass Object
(
[category] => Array
(
[0] => lamps
)
[id] => 2
[code] => canopy2
[path] => public/uploads/nqDT4gEXbF0opPmEpa1cPo5iPSulRoesYcgHiOA3.jpeg
[created_at] => 2018-02-21 11:17:44
[updated_at] => 2018-02-21 11:17:44
)
[2] => stdClass Object
(
[category] => Array
(
[0] => lamps
[1] => panels
)
[id] => 3
[code] => QWE
[path] => public/uploads/0TSrz6j3JJH17XgEs2161mOh8aYgDikujdYwrCWR.jpeg
[created_at] => 2018-02-21 11:18:13
[updated_at] => 2018-02-21 11:18:13
)
)
直接使用MySQL或唯一的方法是操纵结果(在PHP中,在我的情况下)?
可能答案是“你必须使用PHP”,但我不是MySQL专家,这就是问题的原因。
答案 0 :(得分:1)
你应该连接你的category
列,然后按ID分组,就像Patrick在评论中提到的那样。
SELECT GROUP_CONCAT(p.category), r.id ... GROUP BY r.id
您也可以使用JSON_ARRAY或JSON_OBJECT函数来获得类似的结果,但不要忘记将它们分组