我正在学习如何围绕sql和php.我有4个表格结构如下
+-----------+ +------------+ +---------+ +----------+
| Project | | Slide | | Shape | | Points |
+-----------+ +------------+ +---------+ +----------+
| id | | id | | id | | id |
+-----------+ | project_id | | cont_id | | shape_id |
+------------+ +---------+ | x |
| y |
+----------+
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,表格通过id一直链接到点,这意味着项目将包含许多包含许多包含多个点的形状的幻灯片.
我有一个SQL查询
SELECT slide.`id`, shape.`id`, points.`x_point`, points.`y_point`
FROM `project`, `slide`, `shape`, `points`
WHERE 1 = slide.`project_id`
AND slide.`id` = shape.`slide_id`
AND shape.`id` = points.`shape_id`
Run Code Online (Sandbox Code Playgroud)
我想要的是将此查询的结果看起来像这样
[0] => stdClass Object
(
[id] => 27
[x] => 177
[y] => 177
)
[1] => stdClass Object
(
[id] => 27
[x] => 178
[y] => 423
)
[2] => stdClass Object
(
[id] => 27
[x] => 178
[y] => 419
)
[3] => stdClass Object
(
[id] => 27
[x] => 178
[y] => 413
)
[4] => stdClass Object
(
[id] => 27
[x] => 181
[y] => 399
)
[5] => stdClass Object
(
[id] => 27
[x] => 195
[y] => 387
)
[6] => stdClass Object
(
[id] => 27
[x] => 210
[y] => 381
)
[7] => stdClass Object
(
[id] => 27
[x] => 231
[y] => 372
)
[8] => stdClass Object
(
[id] => 27
[x] => 255
[y] => 368
)
[9] => stdClass Object
(
[id] => 27
[x] => 283
[y] => 368
)
... AND CONTINUED FOR A LONG TIME
Run Code Online (Sandbox Code Playgroud)
我想要的是将这个野蛮的垃圾堆转换成更像这样的东西
[9] => stdClass Object
(
[id] => ID OF LIKE SHAPES
[x] => Array(ALL THE X POINTS)
[y] => ARRAY(ALL THE Y Points)
)
Run Code Online (Sandbox Code Playgroud)
我不能为我的生活弄清楚如何将其转换为这样的数组.
如果用我设计的查询无法完成,那么有更好的查询.也许一个抓住积分,然后把它放到一个点数组......我想我只是有一个想法......
新信息,
所以我在这个问题上添加了答案,我不知道这是否是标准方式.如果我不是一个好的解决方案,为了帮助解决其他问题,我也会在这里添加我的思考过程.
有关详细信息,请查看我的答案.
ORM如何与我的算法进行比较?
使用像Doctrine这样的 ORM ,你可以简单地对其进行建模
/**
* @Entity
*/
class Project
{
/**
* @Id @GeneratedValue
* @Column(type="integer")
*/
private $id;
/**
* @OneToMany(targetEntity="Slide", mappedBy="project")
*/
private $slides;
public function __construct()
{
$this->slides = new \Doctrine\Common\Collections\ArrayCollection;
}
}
/**
* @Entity
*/
class Slide
{
/**
* @Id @GeneratedValue
* @Column(type="integer")
*/
private $id;
/**
* @ManyToOne(targetEntity="Project", inversedBy="slides")
* @JoinColumn(name="project_id", referencedColumnName="id")
*/
private $project;
/**
* @OneToMany(targetEntity="Shape", mappedBy="slide")
*/
private $shapes;
}
Run Code Online (Sandbox Code Playgroud)
等等...
当然,这涉及相当多的设置和处理开销,但随着域模型变得更加复杂,您会欣赏 ORM。