0

当使用外部 id 将不同表中的数据链接在一起时,我经常会编写不优雅的代码来获取我需要的信息。这是一个例子:

假设我有一个表 Message,其中包含以下字段:

id, touserId, fromuserId, title, message

touserId 和 fromuserId 分别指的是发送和接收消息的 User 对象的 id。

假设我想显示发送给特定用户的所有消息。在我看来,我最终会写出这样的东西——我知道这很糟糕!

<?
$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>
<?
}
?>

有没有更优雅的方式来访问相关记录中的信息(在这种情况下是发送消息的用户的姓名?)

4

1 回答 1

1

在您的消息模型中,您可以这样做:

public function relations() {
    return array(
        'name' => array(self::HAS_ONE, 'User', 'fromuserId')
    )
}

或者,您可以修改模型以包含 JOIN,以便获取用户名。

于 2012-08-30T16:33:22.247 回答