Yii2-activedataprovider无法获取数据

时间:2016-01-31 07:32:43

标签: php mysql sql yii2 cactivedataprovider

我使用一些$query->andFilterWhere(...)来创建我的查询。

可以通过echo $query->createCommand()->rawSql;

查看最终查询

当我复制最终查询并在phpmyadmin上过去时,获取了2条记录但在ActiveDataProvider中找不到结果。

我错过了哪一点?!

============================================

这是我的代码:

    $query = Camera::find();
$post = Yii::$app->request->post();
$post2 = array_filter((array)$post);

if( count($post2) >0 ){
    foreach($post2 as $k=>$v){
        $query->andFilterWhere([ 'Like' , $k , $v ]);
    } 
}

if($post['State'] > 0){
    $branches = Branch::find()->joinWith('city')->where('state_id='.((int)$post['State']))->all();
    foreach( $branches as &$v){
        $v = $v->brch_id;
    }
    $query->andFilterWhere([ 'IN' , 'brch_id' , $branches ]);    
}

echo $query->createCommand()->rawSql;

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

2 个答案:

答案 0 :(得分:1)

问题在于这个循环:

foreach( $branches as &$v){
    $v = $v->brch_id;
}

我只需将其替换为:

$a = [];
foreach( $branches as $v){
    $a[] = (int)$v->brch_id;
}

并完成,解决了!!!!! :|

答案 1 :(得分:0)

在您的代码中

if( count($post2) >0 ){ // that means all fields filled
    foreach($post2 as $k=>$v){
        $query->andFilterWhere([ 'Like' , $k , $v ]);
    }
}

在此之后,您检查了$post['State'],并将其用于joinWith。我不知道您正在使用什么样的搜索(或者您构建的是什么形式),但似乎您在这两个模型中都在搜索State ...这是正确的行为吗?

如果这是正确的,您能否向我们展示适合您的原始SQL查询,而不是ActiveDataProvider

我可以问为什么不使用课程进行此搜索并将其从Camera扩展?

这与此类似:

public $state // fields that you Camera model don't have.

public function search($params){
    $query = Camera::find();
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

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

    $query->andFilterWhere('like', 'attribute', $this->attribute);
    // same for the others attributes here...

    $query->joinWith(['nameOfRelationWithBranch' => function ($queryBranch) {
        $queryBranch->joinWith(['city' => function ($queryCity) {
            $queryCity->andFilterWhere('state_id', $this->state);
        }]);
    }]);

//echo $query->createCommand()->rawSql;
return $dataProvider;

}