使用find('list')时应用模型关联信息 [英] Apply model association info when using find('list')
问题描述
对于用户模型,我具有以下关联:
For the User model I have the association:
public $belongsTo = array(
'Country' => array(
'foreignKey' => 'country_id',
'conditions' => array( 'Country.code_status' => 'assigned'),
'order' => array( 'short_name_en')
)
);
出于某些原因,我期望使用:
For some reason I was expecting that by using:
$countries = $this->User->Country->find('list');
我将获得一个可能的国家/地区代码列表,以该表格的形式填充下拉列表,并确保这些代码符合协会的定义.
I would get a list of the possible country codes to populate a dropdown in the form and that those would comply to the association definition.
这没有发生,这是可以理解的,因为find()无法(?)检测到我来自哪个关联模型,因此它不能应用所定义的条件/顺序.所以我在AppModel中添加了一个方法,例如:
This is not happening, and it is understandable since the find() cannot (?) detect from which associated model I am coming from, so it can not apply the conditions/order defined. So I added a method to AppModel like:
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'));
我是否错过了模型的工作方式?有更好/更多的蛋糕方式吗?
Did I miss something in the way Models work ? Is there a better/more Cakey way ?
推荐答案
如果您需要所有国家/地区,都应该进行简单查找:
If you need all the countries you should make a simple find:
$countries = $this->Coutry->find('list', [
'conditions' => [
'Country.code_status' => 'assigned'
]
'order' => [
'short_name_en' => 'ASC'
]
]
查询用户模型时,将使用 $ belongsTo
属性,对于每个用户,您将获得其国家/地区.
The $belongsTo
property is used when you query the User model, and for each user you will get his country.
这篇关于使用find('list')时应用模型关联信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!