【问题标题】:Cakephp nested containCakephp 嵌套包含
【发布时间】:2012-06-29 15:29:59
【问题描述】:

我有这个结构和表格的树模型:

Rate:
id, model_name, object_id
1 , SocialPost, 12
public $belongsTo => array(
                'SocialPost' => array(
                    'className' => 'Social.SocialPost',
                    'foreignKey' => 'object_id',
                    'conditions' => array(
                        'Rate.object_id = SocialPost.id',
                    ),
                )
            )

社交邮报: id,file_id

public $hasOne = array(
    'File' => array(
        'className' => 'File',
        'foreignKey' => false,
        'conditions' => array(
            'File.id = SocialPost.file_id',
        ),
    ),
);

文件: id,标题


所有树模型都可以包含

这段代码在 SocialPostsController 中运行良好:

$posts = $this->SocialPost->find('all', array(
        'limit' => 5,
        'contain' => array(
            'File'
        )

    ));

输出:http://pastie.org/private/9ixxufncwlr3tofgp8ozw

但 RatesController 中的这段代码为所有 SocialPost 返回相同的文件:

$mostRated = $this->Rate->find('all', array(
        'limit' => $count,
        'contain' => array(
            'SocialPost' => array(
                'File'
            )
        )

    ));

输出:http://pastie.org/private/lbqryo1gxgvxjb5omfwrw

这里有什么问题?

【问题讨论】:

    标签: cakephp containable


    【解决方案1】:

    我认为你的关联都应该是belongsTo:

    class Rate extends AppModel {
      public $belongsTo = array(
        'SocialPost' => array(
          'className' => 'Social.SocialPost',
          'foreignKey' => 'object_id',
        )
      );
    }
    
    class SocialPost extends AppModel {
      public $belongsTo = array(
        'File'
      );
    }
    

    然后您的查找命令可能如下所示:

    $mostRated = $this->Rate->find('all', array(
      'limit' => $count,
      'contain' => array(
        'SocialPost.File'
      )
    ));
    

    另外,我会仔细检查您的'className' => 'Social.SocialPost' 是否正确。这意味着SocialPost 模型存在于一个名为Social 的插件中。

    【讨论】:

    • Social 是插件,SocialPost 是它的模型。我不能在 SocialPost 中为 File 使用 belongsTo。因为每个帖子都有一个文件,而在 File 模型中我有 SocialPost 的 belongsTo。每个文件都属于许多 SocialPost。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 2014-08-29
    • 1970-01-01
    相关资源
    最近更新 更多