我正在为一个项目做一个简单的任务。
它按预期工作,但在我的Contact Model上使用find方法之后(第二个if),它会抛出一个通知:undefined index "counterCache"
。我想修复此通知以防止将来发生崩溃。
我理解我的代码很乱并且没有完美实现(我不得不更新模型,我不能改变所有连接的方式)。
我阅读了CakePHP的API手册,但我似乎不明白发生了什么。我该如何解决此通知?
注意:
Notice (8): Undefined index: counterCache [CORE/Cake/Model/Model.php, line 2109]
Notice (8): Undefined index: counterCache [CORE/Cake/Model/Model.php, line 2109]
代码:
public function confirm($request_id = null, $contact_that_wants_to_add_you_id = null, $confirm = 0){
$this->layout = 'dashboard';
$this->User->hasMany=$this->User->belongsTo=$this->User->hasManyAndBelongsTo=array();
$this->Contact->hasMany=$this->Contact->belongsTo=$this->Contact->hasManyAndBelongsTo=array();
$this->Contact->belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
));
$requests = $this->Contact->find('all', array(
'conditions' => array(
'Contact.id' => $request_id
)
));
$exists = $this->Contact->find('count', array(
'conditions' => array(
'Contact.user_id' => $this->Auth->user('id'),
'Contact.contact_id' => $contact_that_wants_to_add_you_id
)
));
$confirm_contact = $this->Contact->find('first', array(
'conditions' => array(
'Contact.id' => $request_id,
'Contact.user_id' => $contact_that_wants_to_add_you_id,
'Contact.contact_id' => $this->Auth->user('id')
)
));
if($exists == 0 && $confirm == 1){
$exists = $confirm_contact;
$exists['Contact']['id'] = null;
$exists['Contact']['user_id'] = $this->Auth->user('id');
$exists['Contact']['contact_id'] = $contact_that_wants_to_add_you_id;
$exists['Contact']['friend'] = 1;
$exists['Contact']['confirmed'] = 1;
$confirm_contact['Contact']['confirmed'] = 1;
if($this->Contact->save($exists) && $this->Contact->save($confirm_contact)){
$requests = $this->Contact->find('first', array(
'conditions' => array(
'Contact.id' => $this->Contact->getLastInsertID()
)
));
}
}
$this->set('requests',$requests);
}
更新(固定): 当我重新阅读文档时,解决方案变得非常简单。但是,我仍然不知道为什么会这样,我想知道为什么。如果有人能够回答,请永远感激。
原文:
$this->Contact->belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
));
修复:
$this->Contact->belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'counterCache' => false
));
答案 0 :(得分:0)
您正在错误地设置关联,只能在构建时初始化模型之前使用模型属性。
在此之后您应该使用Model::bindModel()
,否则关联将缺少默认选项,例如counterCache
,这可能会导致您遇到的错误等错误。
$this->Contact->bindModel(
array(
'belongsTo' => array(
'User' => array(
'className' => '...',
'foreignKey' => '...',
// ...
)
)
),
false
);
另请参阅 Cookbook > Associations> Creating and Destroying Associations on the Fly