Getting Value From Related Table

I am trying to retrieve value in a view file and quite confused how I should retrieve value

I have a students table and a categories table, class is created in frontend\models namespace.

Now when I am trying to retrieve the relative value for category column in students view file I am using this code

[

‘label’=>‘Category’,

‘value’=>$Categories->category,

]

I am getting this error:

PHP Notice – yii\base\ErrorException

Undefined variable: Categories

In yii 1.1 I could have easily done like - ‘relationName.category’ that’s all.

Further Upgrading from Yii 1.1 guide for relations, relations are shown like




class Customer extends \yii\db\ActiveRecord

{

    public function getOrders()

    {

        return $this->hasMany('Order', ['customer_id' => 'id']);

    }

}



but looking at my generated code it looks like




 public function getCategories()

	   {

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

	   }



Can someone explain the benefits and how this can be accessed.

Thanks.

In which widget are you trying to show related model value?

If in view file, then I guess it is DetailView widget.

What is relation between Student and Category model? Again, just guessing relation between your Student and Category models is (Many student will by in one category).




echo DetailView::widget([

        'model' => $model,

        ...

        'attributes' => [

            'id',

            ...,

            [

                'name' => 'category_id',

                'value' => $model->categories->category,

            ],

        ],

    ]);



I assume that your Category model has attribute named category.

Thanks, your suggestion worked. but I had to modify the relation method generated by gii.

Generated Method.




public function getCategories()

           {

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

           }



Modified Method




public function getCategories()

           {

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

           }



Can anyone explain what should actually go in there in this code and why gii generated the code like SmartCategories, which didn’t worked. My underlying table name is smart_categories.

is giving table prefix creating more confusion here?




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



Gii tries to define the relation’s class name from that of the underlying table. When you have set the class name for ‘smart_categories’ table as ‘Categories’ manually, then you have to modify the code generated by Gii manually.

Things are much more easier for you when you follow the naming conventions of Yii.

http://www.yiiframework.com/wiki/227/guidelines-for-good-schema-design

This is written for Yii 1.x, but it applies to 2.0.