假设我在一个处理查询的 php 文件中有一个包含大量连接和子查询的查询。注意:我在底部放了一个 $query 的示例
$query = query here;
if ($query) {
return $query->result();
} else {
return false;
}
}
然后在我处理html的php文件中,我有通常的foreach循环,其中一些条件需要进行其他查询,例如;注意:结果包含对象 $query->result()。
foreach ($results as $item) {
$some_array = array();
$some_id = $item->id;
if ($some_id != 0) {
//id_return_other_id is a function that querys a db table and returns the specified column in the same table, it returns just one field
$other_id = id_return_other_id($some_id);
$some_query = another query that requires some joins and a subquery;
$some_array = the values that are returned from some_query in an array
//here i'm converting obj post into an array so i can merge the data in $some_array to item(Which was converted into an array) then convert all of it back into an object
$item = (object)array_merge($some_array, (array)$item);
}
//do the usual dynamic html stuff here.
}
这很好用,但由于我不喜欢在循环中执行大量查询的方式,有没有办法在处理查询的文件中添加 if $some_id != 0 ?我试过了
$query = query here;
//declaring some array as empty when some_id is 0
$some_array = array();
if ($query) {
if ($some_id != 0) {
//same as i said before
$other_id = $this->id_return_other_id($some_id);
$some_query = some query;
$some_array = array values gotten from some query;
}
$qresult = (object)array_merge($some_array, (array)$query->result);
return $qresult;
} else {
return false;
}
}
由于明显的原因,这不起作用,有人有什么想法吗?
此外,如果有办法在 $query 本身中生成这些条件和查询,我会永远爱你。
Ps:演示查询类似于
$sql = "SELECT p.*,up.*,upi.someField,etc..
FROM (
SELECT (another subquery)
FROM table1
WHERE table1_id = 3
UNION ALL
SELECT $user_id
) uf
JOIN table2 p
ON p.id = uf.user_id
LEFT JOIN table3 up
ON .....
LEFT JOIN table4
ON ....
LEFT JOIN table5
ON ....
And so on..etc..
ORDER BY p.date DESC";
$query = mysql_query..