php - Yii2 通过外部表字段和总数进行搜索

标签 php mysql yii2 yii2-advanced-app

我尝试通过外部表进行搜索,如下所示:

2 个表:

人员:

id
name
...

网址:

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 View 显示“显示 40 项中的 1-2 项”而不是“显示 1-2 项” 2 项”

此外,LinkPager::widget 显示的总页数错误

请注意,$dataProvider 从 Controller 传递到 View

$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

我该怎么做才能使分页按照我想要的方式执行?

提前谢谢您,

最佳答案

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

关于php - Yii2 通过外部表字段和总数进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40792608/

相关文章:

php - 我有一个网站,当我将一个页面放在根目录中时它工作正常,但在文件夹中我收到错误?

mysql - Rails Mysql2::Error:使用 count 来获取组

php - 日期格式如 'jan 2010'

gridview - 使用附加图标扩展 GridView ActionColumn

mysql - 为什么会发生pdo异常?它显示未找到数据库驱动程序

jquery - Yii2 Ajax 返回整个页面内容

php -> 从数组中删除包含黑名单中单词的项目

php - 使用自定义列字段而不是 EAV

php - Apigility 中的水化器设置被忽略

php - 多文件 uploader 和查看器 php