Beginner Question

Hi Everybody,

The Yii Framework is my first framework.

I watched this video tutorial.

I tried to made it with my sample but didn’t work. I would like to show the datas from 2 tables in one _view file.

I modified my albums table:


'authors'=>array(self::BELONGS_TO, 'Authors', 'id'),

In the tutorial, the author write out the data from other model similar way:


_view.php:


<?php echo CHtml::encode($data->authors->name); ?>

What is the problem?

I attached the sql tables and the error message.

Hi Comal,

Would you please try to state it comprehensively?

You’d better understand that almost every people (including me) don’t want to open the attached documents to see what’s the problem is. :)

Thank you softdark your answer and that you deleted the spammer’s replies!

I understand that you doubt about the attachments.

I checked again my relations and I found some problems with my code.

I believe, I made a fault with the relations(because I don’t understand well them).

These are my sql tables:


CREATE TABLE `tbl_category` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `name` varchar(30) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;


CREATE TABLE `tbl_author` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `username` varchar(30) DEFAULT NULL,

  `password` varchar(30) DEFAULT NULL,

  `email` varchar(30) DEFAULT NULL,

  `category_id` int(11) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;



I wrote:

in the Author.php model:‘authors’=>array(self::BELONGS_TO, ‘Authors’, ‘id’),

in the _view.php file: <?php echo CHtml::encode($data->authors->name); ?>

I changed:

in the User.php model: ‘categoria’=>array(self::BELONGS_TO, ‘Category’, ‘category_id’),

in the category: ‘authors’=>array(self::HAS_MANY, ‘Author’, ‘id’),

in the user>_view.php: <?php echo CHtml::encode($data->categoria->name); ?>

It is working now, but not working in the admin.php and the create, update files.

I would like to display the categories as like a dropdownlist.

Can you help me?

I see.

  1. You should have defined the FK constraints in the DB level.

Then Gii’s model generator would have automatically created the proper relations. :)

  1. You can use a dropDownList like the following:



$categories = CHtml::listData(Category::model()->findAll(), 'id', 'name');

echo $form->dropDownList($model, 'category_id', $categories);



Check for ‘CActiveForm.dropDownList’ and ‘CHtml.listData’ in the reference. :)

Thank you! :) I will check it!

It’s working! :D I understood the relations. :) So , I’m making it easier this way.

Thank you.