YII中一页中没有关系表的多个模型


Multiple model without relation table in one page in YII

我是YII的初学者。我想问一下,我有两个不同表格的模型,没有关系。实例模型用户和模型产品。所以在用户控制器中,我的代码是

public function actionIndex() {
$model= new Product;
$dataProvider=new CActiveDataProvider('User');
    $this->render('index',array(
        'dataProvider'=>$dataProvider,
    ));
$this->renderPartial('application.views.Product.view',array('model'=>$model));
}

但记录无法显示,只能显示属性。

因此,我可以在一个页面中显示用户记录和产品记录。在CI中,我写了

$data['user']= $this->user->record();
$data['product']=$this->product->record();
$this->load->view('index',$data)

所以,我的问题。我应该如何在yii中编写在一个页面中呈现具有多个表且没有相互关系的多个模型?

您应该在渲染视图中使用renderPartial(),因为正如文档所述,render():

使用布局渲染视图。

此方法首先调用renderPartial来渲染视图(称为内容视图)。然后,它呈现布局视图,布局视图可以将内容视图嵌入到适当的位置。在布局视图中,可以通过变量$content访问内容视图渲染结果。最后,它调用processOutput来插入脚本和动态内容(如果可用的话)。

public function actionIndex() {
$model= new Product;
$dataProvider=new CActiveDataProvider('User');
$this->render('applicationindex',array(
    'dataProvider'=>$dataProvider,
));
}

然后在视图中,

$this->renderPartial('application.views.Product.view',array('model'=>$model));

(IDK this->render部分工作,我尝试使用ur代码,但只出现一条记录,事实上我还有1000条记录)

我用两种不同的方法来解决这个问题,即用多个没有关系的表来渲染多个模型。

我使用小部件的第一个方法

在组件文件夹中创建小部件

class ProductWidget extends CWidget {
public function run() {
$models =      Product::model()->findAll(array('condition'=>'product_token="A"'));
$this->render('category', array(
'models'=>$models   
    ));
}
}

然后在Components/View 中为该小部件创建视图

<?php if($models != null): ?>
<ul>
<?php foreach($models as $model): ?>
<li><?php echo $model->product_token; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

最后在视图(布局/列)文件夹中我写了这个

<?php $this->widget('ProductWidget'); ?>

对于第二种方法(用户控制器中的Function actionIndex)

public function actionIndex() {
$models = Product::model()->findAll(array('condition'=>'Product_token="A"'))
$dataProvider=new CActiveDataProvider('User');
$this->render('index',array(
        'dataProvider'=>$dataProvider,
         'models' => $models,
));

AND Last in View。(视图/用户/索引)

<?php foreach($models as $model):
echo $model->product_token;
endforeach;
?>

我认为第二种方法更好,你可以添加分页之类的。