Apply model association info when using find('

2019-08-10 06:54发布

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 ?

标签: cakephp-2.3
0条回答
登录 后发表回答