Yii框架:与HAS_MANY,BELONGS_TO分页

时间:2012-07-10 14:16:28

标签: yii

我整天都在面对这个问题。

我有2个表服务和日志。每个服务可以有许多日志,每个日志属于一个服务。 我设法为两者生成CRUD功能。 这是我得到的:

应用程序/模型/ Log.php

/**
 * @return array relational rules.
 */
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
    (
        'services' => array(self::BELONGS_TO, 'Service', 'sv_ident_nr'),
    );
}

应用程序/模型/ Service.php

/**
 * @return array relational rules.
 */
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
    (
        'logs' => array(self::HAS_MANY, 'Log', 'sv_ident_nr'),
    );
}

应用程序/ controlelrs / ServiceController.php

/**
 * Displays a particular model.
 * @param integer $id the ID of the model to be displayed
 */
public function actionView($id)
{
    $this->render('view', array
    (
        'model' => $this->loadModel($id),
    ));
}

应用程序/视图/服务/ view.php

<h1>Service: <?php echo $model->ident_nr; ?></h1>
<table class="dataGrid">
<tr>
    <th class="label"><?php echo CHtml::encode($model->getAttributeLabel('proj_nr')); ?></th>
    <td><?php echo CHtml::encode($model->proj_nr); ?></td>
</tr>
<tr>
    <th class="label"><?php echo CHtml::encode($model->getAttributeLabel('customer')); ?></th>
    <td><?php echo CHtml::encode($model->customer); ?></td>
</tr>

<h1>Comments</h1>
<?php foreach ($model->logs as $log): ?>
<div class="comment" id="c<?php echo $log->id; ?>">
    <div class="actions">
        <?php 
            echo CHtml::link('View',array($this->createUrl('../log/view', array('id'=>$log['id']))));
            echo('&nbsp');
            echo CHtml::link('Update',array($this->createUrl('../log/update', array('id'=>$log['id']))));
            echo('&nbsp');
            echo CHtml::link('Delete',array($this->createUrl('../log/delete', array('id'=>$log['id']))));
        ?>
    </div>
    <div class="author">
        <?php 
            echo $log->logger;
        ?>
    </div>
    <div class="time">
        <?php echo date('j F Y \a\t h:i a', $log->created_at); ?>
    </div>

    <div class="content">
        <?php echo nl2br(CHtml::encode($log->comment)); ?>
    </div>

</div><!-- comment -->
<?php endforeach; ?>

问题是:如何在'foreach循环'中对结果进行分页? 感谢

2 个答案:

答案 0 :(得分:0)

基于我之前与你的讨论,我认为这就是你所追求的。

Yii Simple Pagination

答案 1 :(得分:0)

而不是CGridView,请查看docs for CListView。它允许您使用自己的数据模板进行分页,Ajax检索等。这非常值得你花时间......