对于User模型,我有关联:
public $belongsTo = array(
'Country' => array(
'foreignKey' => 'country_id',
'conditions' => array( 'Country.code_status' => 'assigned'),
'order' => array( 'short_name_en')
)
);
出于某种原因,我期望通过使用:
$countries = $this->User->Country->find('list');
我会得到一个可能的国家/地区代码列表,用于填充表单中的下拉列表,并且这些代码符合关联定义。
这种情况没有发生,这是可以理解的,因为find()不能(?)检测我来自哪个关联模型,所以它不能应用定义的条件/顺序。 所以我向AppModel添加了一个方法,如:
public function getAssociationFind( $model, $type='belongsTo' ) {
if (!isset($this->$type)) {
throw new CakeException(__('Association type %s not found in model %s.', $type, $this->name));
}
$typeAssociations = $this->$type;
if (!isset($typeAssociations[$model])) {
throw new CakeException(__('Associated model %s not found.', $model));
}
$conditions = (isset($typeAssociations[$model]['conditions'])) ? $typeAssociations[$model]['conditions'] : array();
$order = (isset($typeAssociations[$model]['order'])) ? $typeAssociations[$model]['order'] : array();
return array( 'conditions' => $conditions, 'order' => $order );
}
这样我可以使用:
$countries = $this->User->Country->find('list',
$this->User->getAssociationFind('Country'));
我是否错过了模特工作的方式?是否有更好/更多的蛋糕方式?
答案 0 :(得分:0)
如果您需要所有国家/地区,则应该进行简单查找:
$countries = $this->Coutry->find('list', [
'conditions' => [
'Country.code_status' => 'assigned'
]
'order' => [
'short_name_en' => 'ASC'
]
]
查询用户模型时,将使用$belongsTo
属性,每个用户都将获得其国家/地区。