我正在开发一个轻型 ORM,它使用基本模型从数据库表中获取所有行。我有多个模型(问题、答案、评论),它们使用每个模型中声明的 protected $table
属性扩展基本模型。这是我在基本模型中获取表行的方法:
public function all() {
$query = "SELECT * FROM {$this->table}";
$statement = $this->database->getConnected($this->connection)->prepare($query);
$statement->setFetchMode(PDO::FETCH_CLASS, 'Core\Database\Collection');
$statement->execute();
return $statement->fetchAll();
}
当我转储结果时,我得到类似的结果:
array(5) {
[0]=>
object(Core\Database\Collection)#31 (4) {
["id"]=>
string(1) "1"
["title"]=>
string(34) "What is your favourite video game?"
}
[1]=>
object(Core\Database\Collection)#244 (4) {
["id"]=>
string(1) "2"
["title"]=>
string(28) "What is your favourite food?"
}
}
我想知道是否可以将每个集合对象组合在一起作为一个大集合对象,而不是作为数组或单个对象返回?
我知道我仍然可以使用 foreach
获得结果,但只是想让它成为一个实际的集合而不仅仅是一个数组。
一个大集合对象
object(Core\Database\Collection) {
all: {
Namespace\Question {
["id"]=>
string(1) "1"
["title"]=>
string(34) "What is your favourite video game?"
},
Namespace\Question {
["id"]=>
string(1) "2"
["title"]=>
string(28) "What is your favourite food?"
}
}
}
最佳答案
我的观点是,使用当前的对象数组可能会更好。但是,您可以获取现有对象,并使用神奇的__set()
方法将值附加到命名数组:
class Collection {
public function __set($name, $value) {
$this->$name[] = $value
}
}
据我所知, PDO::FETCH_INTO
无法与 fetchAll
一起使用,因此您需要一个 while
:
$collection = new Core\Database\Collection;
$statement->setFetchMode(PDO::FETCH_INTO, $collection);
$statement->execute();
while($statement->fetch()){}
return $collection;
应该返回类似的内容:
object(Core\Database\Collection)#1 (2) {
["id"]=>
array(2) {
[0]=>string(1) "1",
[1]=>string(1) "2"
}
["title"]=>
array(2) {
[0]=>string(34) "What is your favourite video game?",
[1]=>string(28) "What is your favourite food?"
}
}
实际上,唯一的其他可能性是拥有一个对象,如您在编辑的示例中所示,其属性是对象数组。您会像您所做的那样执行此操作。只需获取 someNamespace\Question
类的对象数组并将其分配给 Core\Database\Collection
类的另一个对象的属性即可:
$collection = new Core\Database\Collection;
$statement->setFetchMode(PDO::FETCH_CLASS, 'someNamespace\Question');
$statement->execute();
$collection->all = $statement->fetchAll();
return $collection;
应该返回类似的内容:
object(Core\Database\Collection)#1 (1) {
["all"]=> array(2) {
[0]=>
object(someNamespace\Question)#1 (2) {
["id"]=>
string(1) "1"
["title"]=>
string(34) "What is your favourite video game?"
}
[1]=>
object(someNamespace\Question)#2 (2) {
["id"]=>
string(1) "2"
["title"]=>
string(28) "What is your favourite food?"
}
}
}
我不了解 Laravel,视频中的对象/数组语法似乎是本地开发的,所以有点难以破译。
关于php - PDO 将类获取为分组集合对象,而不是数组中的单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49017159/