yii2:如何使用sql查询填充gridview列?

eh57zj3b  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(426)

我有一个带有两列的gridview:id和lastname。
id列工作得很好,但是lastname列有一个问题:我需要执行一个简单的sql查询 SELECT lastname FROM persons 以完成lastname列。
我不知道怎么做。这就是我所尝试的:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        'id',
        [
            'label' => 'Lastname',
            'value' => function() {
                $myQuery = 'SELECT lastname FROM persons';
                return = Yii::$app->getDb()->createCommand($myQuery)->queryAll(); // Problem here.
            }
        ]
    ]
)] ?>

my PersonSearch.php模型的my dataprovider(是否可以在此处添加我的sql查询?):

public function search($params)
{
    $query = Persons::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => [
            'defaultOrder' => [
                'id' => SORT_ASC
            ]
        ],
    ]);

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    $query->andFilterWhere([
        'id' => $this->id,
    ]);

    $query->andFilterWhere(['ilike', 'id', $this->id]);

    return $dataProvider;
}
ijxebb2r

ijxebb2r1#

你有什么东西 $dataprovider ? 如果它加载了persons表中的对象,您可以像这样调用它 id - lastname 或者你可以这样称呼它:

[
            'label' => 'Lastname',
            'value' => function($model) {
                 return $model->lastname;
            }
]

在personsearch.php中

public function rules()
{
    return [
        [['id'], 'integer'],
        [['lastname'], 'safe'],
    ];
}

和搜索功能

public function search($params)
{
    $query = Persons::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => [
            'defaultOrder' => [
                'id' => SORT_ASC
            ]
        ],
    ]);

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    $query->andFilterWhere([
        'id' => $this->id,
    ]);

    $query->andFilterWhere(['ilike', 'id', $this->id]);
    $query->andFilterWhere(['like', 'lastname', $this->lastname]);

    return $dataProvider;
}

如果你有

[
                'label' => 'Lastname',
                'value' => function($model) {
                     return $model->getLastName();
                }
    ]

在中创建函数 Persons.php 带名称的模型 getLastName() ```
public function getLastName(){
$myQuery = 'SELECT lastname FROM persons'; //maybe you have where condition "where id = {$this->id}" ?
$result = Yii::$app->getDb()->createCommand($myQuery)->queryOne();
if($result){
return $result['lastname'];
}
}

如果您有许多行,那么使用 `queryAll()` 并预测结果。

相关问题