【发布时间】:2015-03-05 19:33:37
【问题描述】:
我正在为一个项目做一个简单的任务。
它按预期工作,但是在(第二个如果)我在我的联系人模型上使用 find 方法之后它会抛出一个通知: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
));
【问题讨论】:
-
以后请不要在图片中发布错误信息(或任何文字)——它们无法被搜索到。
-
另外,请务必提及您的确切 CakePHP 版本!如果无法弄清楚错误指向什么,人们将很难为您提供帮助。