When linking data in different tables together using foreign ids, I often end up writing inelegant code to get the information I need. Here is an example:
Say I have a table Message, with the following fields:
id, touserId, fromuserId, title, message
touserId and fromuserId refer to the id of the User objects that are sending and receiving the message respectively.
Say I want to show all the messages sent to a particular user. I end up writing something like this in my view – which I know is bad!
<?
$messages=Message::model()->findAllByAttributes(array("touserId"=>Yii::app()->user->userid));
foreach ($messages as $message) {
$fromuser=User::model()->findAllByAttributes(array("id"=>$message->fromId));
?>
<div>
<h4><?=$message->title;?></h4>
<p>From: <?=$fromuser->name'?>
<p><?$message->body;?></p>
</div>
<?
}
?>
Is there a more elegant way to access the information from related records (in this case the name of the user sending the message?)
In your Message model, you can do this:
Alternatively, you could modify your model to include a JOIN so you get the user names.