Yii2-activedataprovider 不获取数据

Yii2-activedataprovider doesn't fetch data

我使用一些 $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,
]);

在你的代码中你有

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

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

如果那是正确的,您能否向我们展示适合您但不适用于 ActiveDataProvider 的原始 sql 查询?

我能问一下你为什么不使用 class 进行搜索并从 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;

}

问题是这个循环:

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

我只是将其替换为:

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

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