DB table relationship

Hi friends, i am very new YII user, i am trying to play with mysql database

i have two tables

  1. Categories (id,name)

  2. Videos (id, name, code, category_id)

i am able to insert records in table Categories and Videos but i am not able to show result in below format using CGridView

Video ID, Video Name, Video Category Name

when i try to get result it shows category id instead of category name

plz give me solution

You can use relations for this purpose

You can also use a custom function in the Category model which can be used for this purpose




public static function getCatname($id){

 $data=Categories::model()->findById($id);

if(!empty($data))

      return $data->name;

}



You can place this code in your categories model and then where you want to display the name of category use it as




echo Categories::getCatname($data->category_id);



Hope this will help you…

thanks :) it works(after replacing findById to find),

but is there any way to do this work using YII relations??

i am using below code in model relations


'category' => array(self::BELONGS_TO, 'Categories', 'category_id'),

and below code in CGridView


array(

                     

 'name'=>'category',

 'value'=> $data->category,

                     

),

but it gives below error

htmlspecialchars() expects parameter 1 to be string, object given

You passed an ActiveRecord instead of a string. Remember that $data->category points to the whole record, not just the desired attribute. You will need to user $data->category->name.

Thanks Tropi, your hint helped me to find the solution :)

below code works for me (i added single quote ’ around $data->category->name)


  array(

                     

   'name'=>'category',

   'value'=> '$data->category->name',

                     

  ),

thanks everybody :)