简体   繁体   中英

Yii HAS_MANY Relationship with Non Foreign Key and Non Primary Key

I have a following code:

        $country = CountryCodes::model()->with(
            [
                'country_subdivisions' => [
                     CountryCodes::HAS_MANY,
                    'CountrySubDivision',
                    ['country_subdivisions.iso2'=>'t.iso2']
                ]
            ]
        )->findByPk($id);
        $states = $country->country_subdivisions;

I have 2 models/tables CountryCodes and CountrySubDivision. Both table has iso2 column. I want to get the related Subdivision for a Country By ID.

I am not sure why am i getting the following Error:

Relation "country_subdivisions" is not defined in active record class "CountryCodes".

I am a newbie in Yii Framework and I'm using Yii 1.1.x and php 5.6.

At first, you need to define a relationship by overriding relations() method in CountryCodes class.

public function relations() {
    $relations                 = [
        'country_subdivisions' => [
            CountryCodes::HAS_MANY,
            'CountrySubDivision',
            [
                'iso2'         => 'iso2'
            ]
        ]
    ];
    // merge with parents 
    return CMap::mergeArray(
        parent::relations(),
        $relations
    );
}

Then, you can :

$country = CountryCodes::model()->with('country_subdivisions')->findByPk($id);
$states  = $country->country_subdivisions;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM