【问题标题】:AND / OR conditions cakephp FIND for has many associationAND/OR 条件 cakephp FIND for 有很多关联
【发布时间】: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


【解决方案1】:

您可以使用CakePHP's 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;
}

或者,您可以将您的关联设置为仅拉取 commentsvisible(即使采用这种方式,我仍然建议使用上面的“包含”-您不需要分别指定条件时间):

//Post model
public $hasMany = array(
    'Comment' => array(
        'conditions' => array('Comment.visible' => 1)
    )
);

【讨论】:

  • 递归级别-1不行,试试把递归级别改成2就好了
  • @Cakephp.Saint - 这是不正确的。 Containable 必须为 -1 才能工作。除此之外,建议使用递归 2 是非常糟糕的建议。
  • 戴夫:感谢这个建议,真的很有帮助。我知道在 has many 中建立关联,但必须能够看到具有其他值的 cmets。不知道可收容性,对此我真的很感激。
  • 伊戈尔 - 很高兴为您提供帮助! Containable 很棒——你会喜欢的。在您的 AppModel 中将 recursive 设置为 -1,并且永远不要回头。 :)(说真的 - 真的)
  • @Dave 我接受你的观点,但如果我们使用递归 -1,它将只从那个表中获取,而不是相关表知道.. 我们需要在 -1 的情况下输入 1 或 0
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2010-12-17
  • 2022-01-07
相关资源
最近更新 更多