如何在Yii2中使用查询

问题描述 投票:0回答:1

你能帮助我吗。我想要example,但在我的源代码上它变成空emty。我的项目中的查询或源代码是什么?谢谢。

在控制器中

public function actionView($id)
{
    $con = Yii::$app->db;
    $sql = $con->createCommand("SELECT * FROM track where collecting_id=$id ORDER BY collecting_id desc");
    $posts = $sql->query();
    return $this->render('view', [
        'model' => $this->findModel($id),
        'posts' => $posts,
    ]);
}

在视图中

<div class="timeline__items">
<?php
foreach($posts as $row)
{
?>
<div class="timeline__item">
   <div class="timeline__content">
   <h2><?php echo $row['status']; ?></h2>
   <p><?php echo $row['tanggal']; ?></p>
</div>
</div>
<?php
}
?>
</div>

如果查询中的$ id替换为'PMUEI',则结果为result

使用ActiveDataProvider

public function actionView($id)
    {
        $model = $this->findModel($id);
        $hotel = Track::find()->where(['collecting_id' => $model->collecting_id]);
        $posts = new ActiveDataProvider([
            'query' => $hotel,
        ]);
        // $con = Yii::$app->db;
        // $sql = $con->createCommand(
        // "SELECT * FROM track where collecting_id=:collecting_id ORDER BY collecting_id desc",
        // [':collecting_id' => '$id']
        // );
        // $posts = $sql->queryAll();
        return $this->render(
        'view', [
            'model' => $this->findModel($id),
            'posts' => $posts,
        ]);
    }

结果是error

yii yii2 yii2-advanced-app
1个回答
2
投票

将列与用户提供的任何此类输入进行比较时可以很好地绑定参数,或者可以由用户编辑,就像您在$id中作为参数传递的actionView()一样。然后你需要使用queryAll()queryOne(),以防你想要返回多行或单行。

因此,您应该将查询更改为以下内容

public function actionView($id)
{
    $con = Yii::$app->db;
    $sql = $con->createCommand(
        "SELECT * FROM track where collecting_id=:collecting_id ORDER BY collecting_id desc",
        [':collecting_id' => $id]
    );
    $posts = $sql->queryAll();
    return $this->render(
        'view', [
            'model' => $this->findModel($id),
            'posts' => $posts,
        ]
    );
}

除上述之外,您应该使用ActiveRecord。 Active Record提供了一个面向对象的接口,用于访问和操作存储在数据库中的数据。阅读Here让您的生活更轻松。

© www.soinside.com 2019 - 2024. All rights reserved.