cakephp如何通过id查找属于

cakephp如何通过id查找属于,cakephp,orm,find,Cakephp,Orm,Find,在cakephp中,是否有一种使用ORM获取属于特定子项的项的方法。例如,我要获取特定评论记录的相关帖子记录 这是我的评论模式: var $belongsTo = array( 'Post' => array( 'className' => 'Post', 'foreignKey' => 'post_id', 'conditions' => '', 'fields' => '',

在cakephp中,是否有一种使用ORM获取属于特定子项的项的方法。例如,我要获取特定评论记录的相关帖子记录

这是我的评论模式:

var $belongsTo = array(
    'Post' => array(
        'className' => 'Post',
        'foreignKey' => 'post_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);
我尝试过这个,但它会收回每一篇帖子,甚至是那些没有我质疑的评论的帖子:

$this->Post->contain('Comment');
$results = $this->Post->find('all', array(
    'contain' => array(
        'Comment' => array(
            'conditions' => array(
                'id' => 15
           )
        )
)));

还有其他方法吗?

您确定不必在您的条件下指定模型吗

例如:

$this->Post->contain('Comment');
$results = $this->Post->find('all', array(
    'contain' => array(
        'Comment' => array(
            'conditions' => array(
                'Comment.id' => 15
           )
        )
)));

是否确定不必在条件中指定模型

例如:

$this->Post->contain('Comment');
$results = $this->Post->find('all', array(
    'contain' => array(
        'Comment' => array(
            'conditions' => array(
                'Comment.id' => 15
           )
        )
)));

我的研究让我找到了这篇关于包含以下内容的文章:

因此,我的最终解决方案如下:

    $this->Post->unbindModel(array('hasMany' => array('Comment')));

    $results = $this->Post->bindModel(array('hasOne' => array(
            'Comment' => array(
                'foreignKey' => false,
                'conditions' => array('Comment.post_id = Post.id'))
        )));

    $results = $this->Post->find('all', array(
                'conditions' => array(
                    'Comment.id' => 10
                )));

不漂亮但完成了任务:)

我的研究让我找到了这篇关于包含以下内容的文章:

因此,我的最终解决方案如下:

    $this->Post->unbindModel(array('hasMany' => array('Comment')));

    $results = $this->Post->bindModel(array('hasOne' => array(
            'Comment' => array(
                'foreignKey' => false,
                'conditions' => array('Comment.post_id = Post.id'))
        )));

    $results = $this->Post->find('all', array(
                'conditions' => array(
                    'Comment.id' => 10
                )));

不漂亮,但完成了任务:)

它不指定表名就可以工作,问题是它也会收回其他不包含注释的帖子,它们只是有一个空白的注释数组。然而,我希望它只收回包含评论的帖子。我可以使用以下命令修复数组:foreach($results as$key=>$value){if(empty($value['Comment']){unset($results[$key]);}但是我想在优化查询中这样做,sakeI想不出一种方法可以在我脑子里做这件事而不去抓太多东西并过滤掉它。事实上,我认为,如果您确实找到了一种方法来指定这些条件,cake可能仍然会查询所有内容,然后将其过滤掉。您可能需要对此进行SQL查询。它可以在不指定表名的情况下工作,问题是它也会回调其他不包含注释的帖子,它们只是有一个空白的注释数组。然而,我希望它只收回包含评论的帖子。我可以使用以下命令修复数组:foreach($results as$key=>$value){if(empty($value['Comment']){unset($results[$key]);}但是我想在优化查询中这样做,sakeI想不出一种方法可以在我脑子里做这件事而不去抓太多东西并过滤掉它。事实上,我认为,如果您确实找到了一种方法来指定这些条件,cake可能仍然会查询所有内容,然后将其过滤掉。您可能需要为此执行SQL查询。