我正在使用cakephp 2.1和Wamp,这一切都很好。我需要从一个模型(项目)获取一个值(不是id字段)并将其分配给正在保存的记录(设置),如:
SetupsConstroller.php
$this->request->data['Setup']['client_id'] = $this->Setup->$projects['Project']['client_id'];
model setup.php
var $belongsTo = array('Client', 'User',
'Project' => array(
'className' => 'Project',
'foreignKey' => 'pr_number'
)
);
在我的SetupsController中,我得到了项目:
$projects = $this->Setup->Project->find('list', array(
'order' => 'name',
'foreignKey' => 'pr_number',
'fields' => array('Project.pr_number', 'Project.name'),
'conditions' => array('pr_status' => 2)
));
因此,在添加设置时,我从$ projects获得pr_number,一切都很好:
add.ctp
echo $this->Form->input('pr_number', array('label' => 'ASC Project:', 'options' => $projects));
现在,我需要的是项目记录中的另一个值(client_id),并将其分配给我正在保存的设置模型上的列。像我一样在保存之前分配当前的user_id:
SetupsController.php(添加功能)
$this->request->data['Setup']['user_id'] = $this->Auth->user('id'); // this works fine
// Next line needs fixing, returns NULL, Don't know how to access client_id from projects model!
$this->request->data['Setup']['client_id'] = $this->Setup->$projects['Project']['client_id'];
if ($this->Setup->save($this->request->data)) { // then save
试过 加载模块 和其他建议,但没有运气。
我认为这不常见?
有人可以帮忙吗?
非常感谢你。
来自墨西哥蒂华纳的卡洛斯
答案 0 :(得分:1)
自Setup belongsTo Project
:
$selectedProjectId = $this->request->data['Setup']['pr_number'];
$client_id = $this->Setup->Project->find
(
'first',
array
(
'recursive' => -1,
'fields' => array('Project.client_id'),
'conditions' => array('Project.pr_number' => $selectedProjectId)
)
);
// something like this should work
$this->request->data['Setup']['client_id'] = $client_id['Project']['client_id'];
但是,我正在键入此代码而不进行测试,因此第一次尝试时可能无法正常工作。如果不是,请这样做,看看你得到了什么:
debug($client_id); // it should be here
另一方面,复制数据库中的字段可能表明数据库设计存在问题。