【问题标题】:CakePHP models not associating when using ContainableCakePHP 模型在使用 Containable 时没有关联
【发布时间】:2013-09-14 06:31:47
【问题描述】:

我正在使用下面的代码,但 Cakephp 出现错误:“模型“评论”与模型“用户”没有关联”

$this->Paginator->settings = array(
            'contain' => array_merge(
                    array(
                        'Comment' => array(
                            'limit' => 1,
                            'User' => array(
                                'fields' => array('username','id'),
                            ),
                        )
                    ),
            ),
            'recursive' => 1,
            'conditions' => $conditions,
            'limit' => 10,                    
    );

    $posts = $this->Paginator->paginate('Post');

在用户模型中:

public $hasMany = array(
     'Comment' => array(
        'className' => 'Comment',
        'foreignKey' => 'author',
        'dependent' => false
    ),
);

在评论模型中:

    public $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'author',
    )
);

【问题讨论】:

  • 你添加了 `public $actsAs = array('Containable');在您的模型开始时?或者你有没有尝试过?
  • 是的,我被添加了。我的问题的原因是使用 Containable 将评论关联到用户模型:'User' => array('fields' => array('username','id')) 但是 Cakephp 出现错误!
  • 你能在变量声明后立即对 Paginator::settings 进行 var_dump 吗?这样我们就知道 $conditions 包含什么以及这个数组的实际值是什么?

标签: cakephp paginator containable


【解决方案1】:

首先你不应该使用

'recursive' => 1
具有可包含行为。这种行为是根据需要获取相关模型,因此在您的 AppModel 类中添加
public $recursive = 0
。接下来在您的控制器中尝试:
$this->paginate['User'] = array(
            'conditions' => $conditions,
            'limit' => 10, 
            'contain' => array(
                        'Comment' => array(
                            'limit' => 1,
                            'User' => array(
                                'fields' => array('username','id'),
                            ),
                        )
            ),
);

【讨论】:

    猜你喜欢
    • 2012-07-06
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多