CakePHP关系保存


CakePHP Relationship Save

我有以下结构,需要插入目标表中:

目标表:

target_id, client_crop_id, amount

ClientCrop表:

client_crop_id, client_id, crop_id

客户端表:

client_id, client_name

作物表格:

crop_id, crop_name

我的问题是:在插入新的Target时,我的视图有client和crop的id,CakePHP如何知道Target Model的字段client_crop_id是上面引用的两者的并集?我应该在Target的beforeSave()调用一个方法来获取ClientCrop的id吗?

谢谢。

您可以在视图中添加所需字段:

<?php
echo $this->Form->hidden('ClientCrop.cient_id', array('value' => $yourVar)); 
echo $this->Form->hidden('ClientCrop.crop_id', array('value' => $yourVar));
?>

但出于安全考虑,我不建议采用这种方法。试着在你的控制器操作后直接设置它:

<?php
$this->request>data['ClientCrop']['client_id'] = $yourVar;
$this->request>data['ClientCrop']['crop_id'] = $yourVar;
?>

然后应该使用saveAssociated方法。

http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated数组数据null数组选项数组