我试图通过外表搜索如下:
2个表:
人:
id
name
...
URL:
id
peopleID
url
People.php模型:
public function getUrls()
{
return $this->hasMany(Urls::className(), ['peopleID' => 'id'])->select(['url']);
}
PeopleSearch.php模型:
...
$query->joinWith(['urls']);
...
$query
->andFilterWhere(['or',
['like', 'name', $this->name],
...
['like', 'url', $this->name]]
);
这可以搜索在几个字段中的“名称”字段中输入的值,包括外国网址,但在我的视图中,我使用以下内容输入手动分页:
$dataProvider->prepare();
if ($dataProvider->totalCount > 0)
echo Yii::t('app', 'Showing').": <b> ".($dataProvider->pagination->page*$dataProvider->pagination->pageSize+1)."-".($dataProvider->pagination->page*$dataProvider->pagination->pageSize+$dataProvider->count)."</b> ".Yii::t('app', 'of')." <b>".$dataProvider->totalCount."</b> ".Yii::t('app', 'items');
else echo Yii::t('app', 'No results found.');
echo LinkPager::widget(['pagination' => $dataProvider->pagination])
$dataProvider->totalCount
为我提供了联接表中的记录总数,但没有给出people
一个记录的总记录数。例如,如果我在people
表中有2条记录,并且每条记录在“url”表中都有20个url,则index.php视图显示“显示40个项目中的1-2个”,而不是“显示2个项目中的1-2个”
同样LinkPager::widget
显示错误的总页数
请注意$dataProvider
从控制器传递到视图
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
我可以为分页执行我想要的方式做什么?
提前谢谢你,
答案 0 :(得分:0)
在People.php模型中,我建议删除->select(['url'])
:
public function getUrls()
{
return $this->hasMany(Urls::className(), ['peopleID' => 'id']);
}
这样,如果需要,您仍然可以操作这些网址。
在PeopleSearch.php模型中:
...
// $query->joinWith(['urls']);
// This line is the one that makes it so you get 20 results instead of 2, because you actually get one result for each url related to the people returned by the query.
$query->with(['urls']);
// This last line makes sure the model class populates the relation using only one query.
// Two queries will end up being executed to populate both the people and url models,
// however you will get the right amount for $dataProvider->totalCount.
...
if(strlen($this->url) > 0) {
$urlsPeopleIDs = \app\models\Url::find()
->select('peopleID')
->asArray()
->where(['like', 'url', $this->url])
->all();
$query->andWhere(['id' => $urlsPeopleIDs]);
}
// This way you will only filter by url when you receive a url string with lenght > 0.
// If you haven't already, you will need to create a public property called 'url' in your PeopleSearch.php model and add a 'string' or 'safe' rule so you can actually load it's value from post.