首页 > 解决方案 > 带有外部 api 和一对多的 yii gridview 过滤器

问题描述

我正在努力使用 gridview 过滤器。在我的代码中,我有两个吸气剂。

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.
}

我正在尝试做一个过滤器$user->phone->country$user->device->type但我不确定如何以干净的方式从这两者中获得结果。目前,我正在从上面的 2 中获取 id,然后使用结果数组$query->where(['in', 'id', $ids]);

有没有更好的方法来做到这一点?

标签: phpyii2

解决方案


根据要求使用hasManyhasOne方法进行关系

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

而不是在要应用过滤器的主查询中添加此关系

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

探索更多关于 yii2 的关系


推荐阅读