我对这个问题非常绝望,我无法通过谷歌找到任何有用的参考,尽管这应该很容易解决。至少我是这么认为的。
出于性能原因,我替换了一个函数来使用 Postgres 的递归 WITH 查询。我的问题:pg_fetch_object 只返回一行,尽管 pg_num_rows 返回正确的行数(104)。查询本身没问题,我使用其他查询工具得到了干净的结果。
我希望有人可以帮助我,我需要使用 pg_fetch_object 来收集查询结果的所有行,而不仅仅是第一行。请我不知道我做错了什么。这是代码:
public function getSelfAndAncestorsRecursive($id) {
$animal = array();
if ($id != "") {
//Here comes the query string
$query = "WITH RECURSIVE Ancestors AS
(SELECT
animals.id, animals.name, animals.\"animalID\",
animals.sex, animals.\"birthDate\", animals.alive, animals.deleted, cages.\"cageName\",
animals.dummy_strain_info AS strain, animals.dummy_line_info AS line, animals.dummy_gen_info AS gene,
animals.generation, animals.dummy_backcross_info,
animals.\"parentMale\" AS sire, animals.\"parentFemale\" AS dam
FROM animals
LEFT OUTER JOIN cages ON \"homeCage\" = cages.id
WHERE animals.id = ".$id
."UNION ALL
SELECT a.id, a.name, a.\"animalID\",
a.sex, a.\"birthDate\", a.alive, a.deleted, c.\"cageName\",
a.dummy_strain_info AS Astrain, a.dummy_line_info AS Aline, a.dummy_gen_info AS Agene,
a.generation, a.dummy_backcross_info,
a.\"parentMale\" AS Asire, a.\"parentFemale\" AS Adam
FROM animals a
LEFT OUTER JOIN cages c ON a.\"homeCage\" = c.id
INNER JOIN Ancestors n ON a.id = n.sire::int8 OR a.id = n.dam::int8
)
SELECT DISTINCT * FROM Ancestors
ORDER BY id DESC;";
//Parse Query and fetch result
$res = pg_query($query);
while ($row = pg_fetch_object($res) {
//Set array values
$animal["id"] = $row->id;
$animal["name"] = $row->name;
$animal["animal_id"] = $row->animalID;
$animal["birth_date"] = $row->birthDate;
$animal["sex"] = $row->sex;
$animal["alive"] = $row->alive;
$animal["deleted"] = $row->deleted;
$animal["cage"] = $row->cageName;
$animal["strain"] = $row->strain;
$animal["line"] = $row->line;
$animal["gene"] = $row->gene;
$animal["generation"] = $row->generation;
$animal["backcross"] = $row->dummy_backcross_info;
$animal["sire"] = $row->sire;
$animal["dam"] = $row->dam;
}
}
return $animal;
}