Render foreign key in DetailView

Hello all,

I am new to Yii.

After reading the guide I managed to create an app over my existing database (using Gii).

It’s amazing so far :-). CRUD works fine for all tables.

Now I want to extend the generated code.

First of all:

How can I replace the foreign key of a child table with the refering value of the parent table in the DetailView? The constraints are set in the database. Gii created get functions in the model.

Example:




    <?= DetailView::widget([

        'model' => $model,

        'attributes' => [

            'id',

            'user_id',

        ],

    ]) ?>



How can I replace f.e. user_id (FK) with refering usertable.name?

first create relation in your model file like this…


public function getRelUser()

{

    	return $this->hasOne(User::className(), ['u_id' => 'user_id']);

}

in above code


'u_id'

is primary key of User table.

after that add following code in your search model (exampSearch.php)


public function search($params)

    {

        $query = ModelName::find();

	$query->joinWith(['relUser']); // join with user table...

        $dataProvider = new ActiveDataProvider([

            'query' => $query,

        ]);

	


        if (!($this->load($params) && $this->validate())) {

            return $dataProvider;

        }


        $query->andFilterWhere([

               /*     add model attribute for filtering and if add filter on relational attribute so that add that relational attribute in 'safe' */

            'id' => $this->id,

	    'name'=>$this->name,	

        ]);

	

        return $dataProvider;

    }

than in Detail view :




    <?= DetailView::widget([

        'model' => $model,

        'attributes' => [

           [

		 'attribute' => 'id',

		 'value' => $model->id,

	  ],

          [

		 'attribute' => 'user_id',

		 'value' => $model->relUser->name, // or use 'usertable.name'

	  ],

        ],

    ]) ?>



1 Like

Hey Amit, thank you very much!

That was exactly what I was looking for.

It works fine :slight_smile:

If you want to lazy-load the relational data you don’t need to change your search() code.

If you consider that a detail view is for one record it is probably just fine performance-wise to have the extra query here.

Thanks for the hint. Did not think about performance yet.

I managed to access the relational data in the index page too :-).

So it should be ok in the search code.