显示查询返回的行

时间:2016-06-10 06:30:59

标签: yii2

我是yii2的初学者。我的控制器中有一个actionView,我通过了$id。我写了一个查询,从3个表返回连接。我想知道如何在名为view的视图中显示这些行中的特定列。这是我的actionView ...

public function actionView($id)
{

    $select = [
        'user.username',
        'package_subscriptions.package_id',
        'order.order_number',
    ];
    $query = new Query;
    $query->select($select)
            ->from('order')
            ->innerJoin(['user'],'order.user_id = user.id')
            ->innerJoin(['package_subscriptions'],'order.user_id = package_subscriptions.user_id')
            ->all();

    return $this->render('view', [
        // What should I write here
    ]);
}

2 个答案:

答案 0 :(得分:1)

导入查询类

use yii\db\Query;

actionView中的代码

public function actionView($id)
{

    $select = [
        'user.username as username',
        'package_subscriptions.package_id as package_id',
        'order.order_number as order_number',
    ];
    $query = new Query;
    $query->select($select)
            ->from('order')
            ->innerJoin(['user'],'order.user_id = user.id')
            ->innerJoin(['package_subscriptions'],'order.user_id = package_subscriptions.user_id');

    $command = $query->createCommand();
    $list  = $command->queryAll();

    return $this->render('view', [
        'data'=>$list, // pass data to view
    ]);
}

查询返回数组,您可以在查看中使用,如下所示:

foreach($data as $val)
{
  echo $val['username'];
  echo $val['package_id'];
  echo $val['order_number'];
}

答案 1 :(得分:1)

试试这个

public function actionView($id)
{

    $select = [
        'user.username',
        'package_subscriptions.package_id',
        'order.order_number',
    ];
    $query = new Query;
  $results=  $query->select($select)
            ->from('order')
            ->innerJoin(['user'],'order.user_id = user.id')
            ->innerJoin(['package_subscriptions'],'order.user_id = package_subscriptions.user_id')
            ->all();

    return $this->render('view', [
       'results'=>$results
    ]);
}

view.php

<?
foreach($results as $result){
?>
username:<?=$result['username']?>
<br>
Package id:<?=$result['package_id']?>
<br>
order number:<?=$result['order_number']?>
<?
}
?>