Yii2 Howto related column three deep active record

How can I show street in my user model through a postcode model

I have three tables:

user: id, name, postcode_id

posctode: id, postcode, street_id

street: id, street.

How can I show street in my user\index.php through active record?

What code can I use where?

something like

(user:postcode_id -> postcode:id) -> (postcode:street_id -> street:id) -> street

I did manage to show the postcode in my user form, but need help showing the street.

this works… in the usermodel


public function getPostcode() {

        return $this->hasOne(Postcode::className(), ['id' => 'postcode_id']);

    }


public function getStreet() {

        return $this->postcode->hasOne(Street::className(), ['id' => 'street_id']);

    }



in the view\user\index.php




            ['attribute' => 'postcode', 'value' => 'postcode.postcode'],

            ['attribute' => 'street', 'value' => 'street.street'],



And the user_search should look like:




    public $postcode;

    public $street;

 

//...


    public function search($params) {


        $query = User::find();

        $query->joinWith(['postcode']);

        $query->join('LEFT OUTER JOIN', 'street',

	                'postcode.street_id = street.id');


//...




        $dataProvider->sort->attributes['postcode'] = [

            'asc' => ['postcode.postcode' => SORT_ASC],

            'desc' => ['postcode.postcode' => SORT_DESC],

        ];


        $dataProvider->sort->attributes['street'] = [

            'asc' => ['street.street' => SORT_ASC],

            'desc' => ['street.street' => SORT_DESC],

        ];


//...


                ->andFilterWhere(['like', 'postcode.postcode', $this->postcode])

                ->andFilterWhere(['like', 'street.street', $this->street]); 



Hello, thank you for sharing your solution. I’m a bit late but I wanted to add that you can also just type the three (or more) relations as long as they are well configured in the model files (street relation in postcode model, postcode relation in user model), like this:

in the view\user\index.php:


['attribute' => 'postcode.postcode'],

['attribute' => 'postcode.street.street'],

This would work without the need to edit the model files. Although "UserSearch" would still need to be configured for filtering and sorting to work.