访问&在Yii中显示子表数据

时间:2016-03-19 08:37:20

标签: php yii

您好我遇到了基于父表的查看子表数据等问题。

表格结构

主题

id  |  name  |  
--------------
 1  |  xyz   |

id  |  topic_id  |  topic_body  |
---------------------------------
 1  |     1      |     abc      |

topic_idforeign_key

我的工作

SiteController

$topic = Topic::model()->findAll(array('order'=>'id DESC', 'limit' => 5,'condition'=>'approved=:approved', 'params'=>array(':approved'=>1)));

$this->render('index', array('topic'=>$topic));

查看

<?php
foreach($topic as $topic)
{
    $topics = $topic->title;
    ?>
      <p>
        <a href="view/id/<?php echo $topic->id; ?>">
          <b><?php echo $topics;?></b>
        </a>   
      </p>  
    <?php   
}
?>

现在显示主题,但是如何根据子表中的主题显示topic_body?

1 个答案:

答案 0 :(得分:0)

您已经有了一个主题模型,最好定义一个帖子模型并在模型之间创建关系。

class Post extends CActiveRecord {
    ...
    public function relations() {
        return array(
            'topic'=>array(self::BELONGS_TO, 'Topic', 'topic_id')           
        );
    }
}

重写主题模型并向Post模型添加关系(One Topic有很多帖子)

class Topic extends CActiveRecord {
    ... 
    public function relations() {
        return array(
            'posts'=>array(self::HAS_MANY, 'Post', 'topic_id')
        );
    }
}

现在获取您的主题,并使用->with在结果中包含所有帖子:

$topics = Topic::model()->with('posts')->findAll(array('order'=>'id DESC', 'limit' => 5,'condition'=>'approved=:approved', 'params'=>array(':approved'=>1)));
foreach($topics as $topic){
    echo $topic->title;
    foreach($topic->posts as $post){
         echo $post->topic_body;
    }
}