我正在使用此函数helps
根据参数列出表中的项目:(我包含了大部分代码,但您实际上可以只关注 mysql 查询)
function list_helps($by,$value,$page = -1,$ipp = 20){
/* Yes I concatenate querys... so i use some variables to help it a bit */
$sql = 'SELECT helps.* FROM helps ';
$where = ''; $orderBy = ''; $in = ''; $join = ''; $limit = ''; $resultitems = ''; $header = '';
if($page > 0) $limit = 'LIMIT '.$page*$ipp.', '.($page+1)*$ipp; else $limit = 'LIMIT 10';
switch($by){
case 'byuser':
$where = 'WHERE id_user ='.$value;
$orderBy = 'ORDER BY id DESC';
break;
case 'byfriend':
$sql = 'SELECT
h.*,
f.*
FROM (
SELECT
id,
CASE followerid WHEN '.$value.' THEN followingid ELSE followerid END AS friend_id
FROM friends
WHERE acepted = 1
AND (followerid = '.$value.' OR followingid = '.$value.')
) AS f
INNER JOIN helps AS h ON h.id_user = f.friend_id
ORDER BY h.id DESC';
break;
default:
break;
}
$sql .= $where.' '.$orderBy.' '.$limit;
$res = cache_query($sql,'',60*60*5);
/* checks in cache first, if not; executes query.. next code it's to render content */
}
还有更多案例,但让我们专注于这两个。
它们都提供被请求的“帮助”(如果是用户,或者如果用户的朋友);问题是当我试图检索那些评论时(比如博客文章的位置);我正在这样做:
res = cache_query('SELECT help_replies.content, help_replies.date,
help_replies.offers, help_replies.accepted, help_replies.id_responds,
usuarios.first_name, usuarios.last_name, usuarios.avatar,usuarios.id
FROM help_replies left join usuarios
ON help_replies.id_user = usuarios.id
WHERE help_replies.id_responds = '.$this->id.'
ORDER BY help_replies.id ASC', '', 30);
foreach($res as $obj) {
/* $obj['id_responds'] */
}
}
问题是help_replies.id_responds
引用了该项目,所以当情况是“byuser”时很好;但是当案例是'byfriend'时,这个字段会丢失(所以总是显示相同的评论)
结论:
- byuser -> 帮助很好&评论很好
- byfriend -> 帮助很好(这很奇怪)& 评论错误
知道为什么 $this->id 与 (JOINED) 查询不符吗?
-编辑-
$this->id 来自这个构造方法(我省略了很多属性)
function __construct($item) {
$this->id = $item['id'];
$this->id_user = $item['id_user'];
..
}
并且 $item 是 foreach 的一次迭代(因此它返回的行转换为数组)
穆哈斯·格拉西亚斯