【发布时间】:2012-11-26 10:57:40
【问题描述】:
我有一个模型帖子,它与模型评论有很多关联。
Post 有一个主键 post_id,它是 Comment 的外键。
这两个都有一个可见的列。
我有一个关于 Post.visible 选项的有效查询,我需要添加 AND 以查找具有 Post.visible 值之一的所有帖子。
对于这些帖子,我需要所有 Comment.visible 值 = 1 的评论。
我的代码:
$conditions = array(
"OR" => array(
"Post.visible" => array(
1,
2,
3,
4
),
),
"AND" => array (
"Comment.visible" => 1
)
);
$result = $this->Post->find('all', array(
'order' => 'Post.created DESC',
'conditions' => $conditions
));
没有 AND 的结果是好的(但我也得到可见 = 0 的评论)。
当我将条件 "Comment.visible" => 1 放入 has manyassociation 时,效果很好(但我不能这样做,因为我需要在其他地方获取可见性为 0 的评论)。
使用 并显示此错误:
错误:SQLSTATE[42S22]: 找不到列:1054 'where 子句'中的未知列 'Comment.visible'
当我转储 SQL 时,在 SELECT 子句中甚至不匹配 cmets 表(也不在 LEFT JOIN 中)。
【问题讨论】:
-
不能直接查询hasMany方向的条件。你需要在这里进行子查询。只有 HasOne、BelongsTo 可以在单个查询中直接使用条件查询。
-
所以基本上我构建了 $this->Comment->find('first', conditions=>array('Comment.visible' => 1, 'Comment.post_id' => 'Post. post_id'));其他地方然后我可以在“主要”条件下使用它吗?性能怎么样?
-
@IgorLacik 您是否尝试过使用
contain选项?
标签: cakephp cakephp-2.1