简体   繁体   中英

yii gridview filter with external api and one to many

I am struggling with gridview filter. In my code I have two getters.

public function getPhone()
{
    return UserPhone::find()->where(['user_id' => $this->id])->orderBy('updated_at DESC')->one();
}

public function getDevice()
{
    return ExternalAPiHelper::getDeviceInfo($this->id); // this will make a call to external db, and fetching result from there.
}

I am trying to do a filter for $user->phone->country and $user->device->type I am not sure how I can get the results from both of these in a clean manner. Currently, I am fetching the id from the above 2 and then using the result array in $query->where(['in', 'id', $ids]);

Is there any better way to do this?

use hasMany or hasOne method for relation as per requirement

public function getPhone(){
    return $this->hasOne(UserPhone::className(),['user_id' => 'id'])
           ->orderBy('updated_at DESC');
}

than add this relation in main query where you want to apply filter

$query = ....Model query where you define above relations
$query->joinWith('phone')
$query->andWhere(['LIKE','country',$countryName])

explore more about yii2 relations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM