Getting relational data

I have a User table and a Trip table with a many-to-many relationship managed by the Trip_User table. I have established foreign key constraints (MySql - InnoDB).

Here is the relation code from the Trip model:


	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'tblItems' => array(self::MANY_MANY, 'Item', '{{trip_item}}(trip_id, item_id)'),

			'tblUsers' => array(self::MANY_MANY, 'User', '{{trip_user}}(trip_id, user_id)'),

		);

	}



For each Trip record, I save the id of the user that created the trip in field cuser_id. In my _view.php file for Trip, I am trying to get username (which is in User table) from the cuser_id of the Trip table. Here is the code I am using:


	<b><?php echo CHtml::encode($data->getAttributeLabel('cuser_id')); ?>:</b>

	<?php //echo CHtml::encode($data->cuser_id); ?>

	<?php echo CHtml::encode($data->tblUsers->username); ?>

	<br />



I tried using


<?php echo CHtml::encode($data->tblUsers[0]->username); ?>

which returned the username for the first record in my view, but all other records had a blank cuser_id on the screen.

I’m sure this should be really simple, but I can’t figure it out.

The use case you describe sounds more like a BELONGS_TO relationship from Trip to User (with cuser_id specified as FK). Use $data->tblUsers->username to access the user name.

/Tommy

Thanks, Tommy. Although, I should have specified that the reason there is a many-to-many relationship between the User and Trip table is because in the application itself, many users can subscribe to many trips. That is a form I will need to tackle later on in my project.

However, you did expose a design flaw to get my user name in this case. I created the foreign key and added a new BELONGS_TO relationship in my model and everything works. Thanks again!