Display foreign key name instead of the id used for the FK itself

Hi,

How can I display the column ‘name’ of a row from a foreign table?

DATABASE SITUATION

Two tables are set:

play_store_category => idcategory (PK) | name

game => idgame (PK) | name | idplaystorecategory (FK)

WHAT I NEED TO DO

I need to display the column ‘name’ from table when I am viewing a game detail. What is happening today is that it simply shows the idcategory (foreign key). I need to get the name from that foreign key.

I tried doing this:

[color="#FF0000"] [

			'label' => 'label' => 'PLAY STORE CATEGORY NAME',


			'value' => $model->idplaystorecategory->name,


		][/color]

But of course it is not working.

HOW MY CODE IS

Generating models,controllers and views by GII CRUD, these are the generated files:

‘GameController.php’:


<?php


namespace app\controllers;


use Yii;

use app\models\Game;

use app\models\GameSearch;

use yii\web\Controller;

use yii\web\NotFoundHttpException;

use yii\filters\VerbFilter;


/**

 * GameController implements the CRUD actions for Game model.

 */

class GameController extends Controller

{

    public function behaviors()

    {

        return [

            'verbs' => [

                'class' => VerbFilter::className(),

                'actions' => [

                    'delete' => ['post'],

                ],

            ],

        ];

    }


    /**

     * Lists all Game models.

     * @return mixed

     */

    public function actionIndex()

    {

        $searchModel = new GameSearch();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);


        return $this->render('index', [

            'searchModel' => $searchModel,

            'dataProvider' => $dataProvider,

        ]);

    }


    /**

     * Displays a single Game model.

     * @param integer $id

     * @return mixed

     */

    public function actionView($id)

    {

        return $this->render('view', [

            'model' => $this->findModel($id),

        ]);

    }


    /**

     * Creates a new Game model.

     * If creation is successful, the browser will be redirected to the 'view' page.

     * @return mixed

     */

    public function actionCreate()

    {

        $model = new Game();


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->idgame]);

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }


    /**

     * Updates an existing Game model.

     * If update is successful, the browser will be redirected to the 'view' page.

     * @param integer $id

     * @return mixed

     */

    public function actionUpdate($id)

    {

        $model = $this->findModel($id);


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->idgame]);

        } else {

            return $this->render('update', [

                'model' => $model,

            ]);

        }

    }


    /**

     * Deletes an existing Game model.

     * If deletion is successful, the browser will be redirected to the 'index' page.

     * @param integer $id

     * @return mixed

     */

    public function actionDelete($id)

    {

        $this->findModel($id)->delete();


        return $this->redirect(['index']);

    }


    /**

     * Finds the Game model based on its primary key value.

     * If the model is not found, a 404 HTTP exception will be thrown.

     * @param integer $id

     * @return Game the loaded model

     * @throws NotFoundHttpException if the model cannot be found

     */

    protected function findModel($id)

    {

        if (($model = Game::findOne($id)) !== null) {

            return $model;

        } else {

            throw new NotFoundHttpException('The requested page does not exist.');

        }

    }

}

‘view.php’ (view view for game model):


<?php


use yii\helpers\Html;

use yii\widgets\DetailView;


/* @var $this yii\web\View */

/* @var $model app\models\Game */


$this->title = $model->name;

$this->params['breadcrumbs'][] = ['label' => 'Games', 'url' => ['index']];

$this->params['breadcrumbs'][] = $this->title;


?>

<div class="game-view">


    <h1><?= Html::encode($this->title) ?></h1>


    <p>

        <?= Html::a('Update', ['update', 'id' => $model->idgame], ['class' => 'btn btn-primary']) ?>

        <?= Html::a('Delete', ['delete', 'id' => $model->idgame], [

            'class' => 'btn btn-danger',

            'data' => [

                'confirm' => 'Are you sure you want to delete this item?',

                'method' => 'post',

            ],

        ]) ?>

    </p>


    <?= DetailView::widget([

        'model' => $model,

        'attributes' => [

            'idgame',

            'name',

            'idplaystorecategory',

[color="#FF0000"]			[

				'label' => 'PLAY STORE CATEGORY NAME',

				'value' => $model->idplaystorecategory->name,

			][/color]

        ],

    ]) ?>


</div>




[

	'label' => 'PLAY STORE CATEGORY NAME',

	'attribute' => 'play_store_category.name',

]




If you need custom formatting you can do something like this:





[

	'attribute' => 'contactHistory',

	'format' => 'raw',

	'value' => implode('<br/>', array_map(function($model){ return $model->date . ' : ' . $model->subject;}, $model->contactHistories))

],



how can i search by name instead by pk in a cgridview, sorry for my english

Got an exception:

Unknown Property – yii\base\UnknownPropertyException

Getting unknown property: app\models\Game::play_store_categoryname

All the answers to my questions on youtube channel DoingITeasyChannel (video ‘Yii2 Lesson - 9 Advance Template CRUD Generation using the Gii Tool’)

It is SOLVED!

Thanks anyways flarpy !

1 Like