为了减少查询的数量,当我从我的数据库中选择一些东西时,我想启动最好的一个,它可以是以下之一:
1- SELECT ... FROM cities JOIN states ON city.stateID = state.stateID WHERE city.cityID = ...
2- SELECT ... FROM cities WHERE city.cityID = ...
3- SELECT ... FROM states WHERE state.stateID = ...
如果我执行第一个,我将不需要(可能)执行第二个和第三个查询,因为我已经有了数据。
但是如何在两个或多个实例类之间共享单个连接查询的结果?假设我必须首先使用第三个查询,因为我已经有了来自 3 的数据,你将如何从你的代码中控制 City 实例的创建?
<?php
class City
{
protected $state;
function getState()
{
if(!$this->state)
$this->state = State::getByID($this->stateID);
return $this->state;
}
// since i may already have (in the outer scope) the $state instance...
// to avoid an unnecessary query (State::getByID()) i allow to set the state:
function setState(State $state)
{
if($state->stateID == $this->stateID)
$this->state = $state;
else
throw new Exception("This City doesn't belong to the given State");
}
}
这个对吗?我做得对吗?
例如,我可以像这样创建“地址”的构造函数:
<?php
class Address
{
const PREFETCH_CITY = 1;
const PREFETCH_STATE = 2;
const PREFETCH_ALL = 3;
construct($cityID, $prefetch = 0)
{
if($prefetch & static::PREFETCH_CITY)
// i use the "JOIN cities" query (i also set $this->city)
elseif($prefetch & static::PREFETCH_STATE)
// i use the "JOIN states" query (i also set $this->state)
elseif($prefetch & static::PREFETCH_ALL)
// i use the "JOIN states JOIN cities" query
// (i preset also both $this->city and $this->state)
else
// i don't use any JOIN, i just get the city
}
}
实际上现在我认为构造函数应该在一个单独的类中,但无论如何......
一般来说......我能读到关于这个论点的什么?欢迎书籍、教程
希望清楚,我的英语很糟糕......非常感谢您提前:)