【问题标题】:Multiple model without relation table in one page in YIIYII中一页没有关系表的多个模型
【发布时间】:2013-11-21 07:31:31
【问题描述】:

我是 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 的一页中呈现具有多个表且彼此没有关系的多个模型?

【问题讨论】:

    标签: php yii model renderpartial


    【解决方案1】:

    你应该在渲染视图中使用 renderPartial(),因为作为it's documented,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));
    

    【讨论】:

      【解决方案2】:

      (IDK this->renderPartial 工作,我尝试使用你的代码但只出现一条记录,实际上我还有 1000 条记录)

      我用 2 种不同的方法解决了这个问题,用于渲染具有多个无关系的多个表的多个模型。

      我使用小部件的第一种方法。

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

      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; ?>
      

      最后在 Views (layouts/column) 文件夹中我写了这个

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

      对于第二种方法(用户控制器中的函数 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 最后在视图中。 (浏览量/用户/索引)

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

      我觉得第二种方法更好,你可以加分页什么的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-14
        • 2021-12-17
        相关资源
        最近更新 更多