【问题标题】:How to encode SQL Query result in a View using Yii 2.0?如何使用 Yii 2.0 在视图中编码 SQL 查询结果?
【发布时间】:2015-06-30 08:29:55
【问题描述】:

在 Yii 2.0 中,我试图将查询结果编码或打印为 XML 格式,以便使用 REST 访问这些数据,但是当我将查询结果(位于 ActiveController 中)推送到de view,我得到一个巨大的 html 代码和里面的查询结果。

这是我的ActiveController,我的函数actionSql() 用于渲染sql.php 视图:

class EventController extends ActiveController{

    public $modelClass = 'app\models\Event';

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ]);
    }


    public function actionSql(){
        $rows = (new Query())
        ->select(['ta.id', 'e.name', 'e.desc', 'u.place', 'u.date'])
        ->from(['ta' => 't_area'])
        ->innerJoin('event e', 'ta.id = e.t_area_id')
        ->innerJoin('ubic u', 'e.id = u.event_id')
        ->where([
            'ta.id' => 1,
            'dayname(u.date)' => 'Monday'
            ])
        ->all();

        return $this->render( 'sql', [
            'rows' => $rows,
        ]);
    }
}

===========================
sql.php (The View)

<?php
    use yii\helpers\Html;
    use yii\grid\GridView;
?>
<?php 
    foreach ($filas as $fila){
        foreach ( $fila as $key=>$value ){
            echo $key . ' => ' . $value . '<br>';
        } 
        echo '<br>';
    }
 ?>

非常感谢。希望能找到答案!

【问题讨论】:

  • 尝试返回行而不渲染它们,return $rows

标签: php model-view-controller yii yii2


【解决方案1】:

您可以使用renderPartial() 来呈现您的视图而不应用布局。

但是您在 sql 视图中使用的格式不是 XML... 你应该试试:

public function actionSql()
{
    $rows = ....... ;

    \Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
    return $rows;
}

Yii2 Cookbook 中阅读有关响应格式的更多信息。

你也应该阅读这个:RESTful Web Services with Yii2

【讨论】:

    【解决方案2】:

    非常感谢您的时间伙伴。解决方案是返回 rows 变量:

    public function actionSql(){
        $rows = (new Query())
        ->select(['ta.id', 'e.name', 'e.desc', 'u.place', 'u.date'])
        ->from(['ta' => 't_area'])
        ->innerJoin('event e', 'ta.id = e.t_area_id')
        ->innerJoin('ubic u', 'e.id = u.event_id')
        ->where([
            'ta.id' => 1,
            'dayname(u.date)' => 'Monday'
            ])
        ->all();
        //The solution is!: 
        return $rows;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多