【发布时间】:2014-03-03 05:11:38
【问题描述】:
让我的协会在这里工作真是太棒了。每次我在事件控制器上运行视图操作并使用 var_dump 时,我只返回事件信息,没有公司信息,这就像它忽略了我的关联,更烦人的是没有错误消息。
Events 表有一个名为 Company_ID 的字段,而 Companies 表有一个 ID 字段。 (是大写的 Company_ID 和 ID)。
class Event extends AppModel{
public $name = "Events";
// public $belongsTo = 'Company';
public $belongsTo = array('Company'=>array(
'className' => 'Company',
'foreignKey'=>'Company_ID'
));
//public $hasOne = 'Company';
/*public $hasOne = array('Company'=>array(
'className' => 'Company',
'foreignKey'=>'Company_ID'
));*/
}
App::uses("AppModel", "Model");
class Company extends AppModel{
public $name = "Company";
}
调用控制器。
public function view() {
$id = $this->request->params['id'];
$this->set(
'event',
$this->Event->find(
'first',
array('conditions' => array('Event.id' => $id))
)
);
}
【问题讨论】:
-
您必须告诉 cake 您在 Company 中的主键是 ID 而不是 id:
public $primaryKey = 'ID'; -
CakePHP does not save associated Models 的可能副本。见
This is by far the most common cause of "why is my model logic not being executed" questions.。 -
@arilia 刚刚尝试过,这似乎没有任何效果,而且我认为控制器似乎对视图操作的大写“ID”没有问题. public function view() { $id = $this->request->params['id']; $this->set('event', $this->Event->find('first', array('conditions' => array('Event.id' => $id)))); }
-
@AD7six 是文件名,其中一些是复数形式与单数形式。我将 Events.php 更改为 Event.php,将 Companies.php 更改为 Company.php,这似乎可以解决问题。
-
@NateGates sweet - 请把它放在答案中并接受它=)。
标签: php database cakephp controller belongs-to