Apply model association info when using find('list')

本秂侑毒 提交于 2019-12-11 13:44:46

问题


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.

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 );
}

This way I can use:

$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 ?

来源:https://stackoverflow.com/questions/33052432/apply-model-association-info-when-using-findlist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!