Masoud Nazari
Masoud Nazari

Reputation: 496

Yii2-activedataprovider doesn't fetch data

I use some $query->andFilterWhere(...) to create my query.

and can see the final query by echo $query->createCommand()->rawSql;

when I copy the final query and past it on phpmyadmin, 2 record fetched but no result found in ActiveDataProvider.

Where is the point that I miss that?!

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

This is my code:

    $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,
]);

Upvotes: 1

Views: 367

Answers (2)

Masoud Nazari
Masoud Nazari

Reputation: 496

The problem was this loop:

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

I just replace it by:

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

and DONE, Solved!!!!! :|

Upvotes: 1

Clyff
Clyff

Reputation: 4076

In your code you have

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

And just after that you have a check for $post['State'] and you are using it for a joinWith. I Don't know what kinda search you are using (or what form did you build), but it seems you are searching for State in this both models... is that the correct behavior?

If that's correct, can you show us the raw sql query that worked for you, but not with ActiveDataProvider?

And can i ask why don't you use a class for this search and extends it from Camera?

It would be something similar to this:

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;

}

Upvotes: 0

Related Questions