1

我有一个模型帖子,它与模型评论有很多关联。

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 子句中甚至不匹配(也不在 LEFT JOIN 中)。

4

1 回答 1

3

您可以使用CakePHP 的 Containable Behavior来限制另一个模型的结果,如下所示(这应该可以工作,但可以根据您的需要随意调整):

//Post model
public $recursive = -1;

public $actsAs = array('Containable');

public function getPosts() {
    $posts = $this->find('all',
        array(
            'conditions' => array(
                'Post.visible' => 1
            ),
            'contain' => array(
                'Comment' => array(
                    'conditions' => array('Comment.visible' => 1)
                )
            )
        )
    );
    return $posts;
}

或者,您可以将您的关联设置为仅拉取comments那些visible(即使采用这种方式,我仍然建议使用上面的“包含” - 您不需要每次都指定条件):

//Post model
public $hasMany = array(
    'Comment' => array(
        'conditions' => array('Comment.visible' => 1)
    )
);
于 2012-11-26T14:49:23.510 回答