shahidmau
(Mshahid85)
December 20, 2011, 7:54am
1
Hi friends, i am very new YII user, i am trying to play with mysql database
i have two tables
Categories (id,name)
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
perochak
(Amjad Mughal)
December 20, 2011, 8:23am
2
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…
shahidmau
(Mshahid85)
December 20, 2011, 9:35am
3
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
Tropi
(Daniel Lang)
December 20, 2011, 10:01am
4
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.
shahidmau
(Mshahid85)
December 20, 2011, 10:53am
5
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