【发布时间】:2014-01-28 20:54:00
【问题描述】:
我有两张桌子:
Property (..., postcode_id, ...)
Postcode (id, postcode, latitude, longitude)
关系:
class Property extends AppModel {
public $belongsTo = array(
'Postcode' => array(
'className' => 'Postcode'
)
);
class Postcode extends AppModel {
public $hasMany = array(
'Property' => array(
'className' => 'Property'
)
);
我希望发生的事情:
- 在属性添加表单中输入邮政编码。
- 检查输入的邮政编码是否在邮政编码表中。
- 如果没有,那么一些逻辑(可能添加它,现在只返回验证错误)。
- 如果是,则在 Properties.postcode_id(外键)中记录 Postcode.id。
我想不出用蛋糕做这个的最佳方法。执行检查并将其添加到要添加的数据的自定义属性验证函数?还是在 beforeValidation 中?还是 Cake 会处理这个问题?
谢谢!
编辑
根据答案,我认为这是最好的解决方案...
我认为这是更好的方法,因为它也可以验证。感谢 Anubhav 让我走上正轨!
根据 Anubhav 的回答,在 Postcode 模型中:
public function checkPostcode($postcode = null){
$record = $this->find('first', array(
'conditions'=>array('postcode' => $postcode),
'fields' => array('id')
));
if (!empty($record)){
return $record['Postcode']['id'];
} else {
return false;
// Logic for finding and adding new postcode
}
}
但是在属性模型中:
public $validate = array(
'postcode' => array(
'exists' => array(
'rule' => 'postcodeExists',
'message' => 'Postcode does not exist'
)
)
);
public function postcodeExists($check) {
$id = $this->Postcode->checkPostcode($check);
if ($id) {
$this->data['Property']['postcode_id'] = $id;
return true;
}
return false;
}
public function beforeSave($options = array()) {
unset($this->data['Property']['postcode']);
}
通过修改要保存在这里的值,控制器保持精简,并且,与其确保邮政编码是真实的然后找到 id,两者都是同时完成的,因此只需要一个查询。
【问题讨论】:
-
你有什么问题?
-
如何在 Postcode 表中的 Propery add 表单中找到用户输入的邮政编码记录,如果存在,将该记录的 ID 放在 postcode_id 外键字段中属性表?
标签: cakephp model foreign-keys relationship model-associations