gpt4 book ai didi

php - Yii2:对 GridView 中的关系计数列进行排序

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:35:07 26 4
gpt4 key购买 nike

[编辑 2]

我很难按定义为模型“标签”上的关系 setter/getter 的“topicCount”进行排序。一个主题可以有很多标签,并希望根据包含该标签的主题的数量对标签进行排序。

在我的模型/Tag.php 中:

public function getTopicCount()
{
return TopicTag::find()->where(['tag_id' => $this->id])->count();
}

在我的 views/tag/index.php 中:

<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
[
'attribute'=>'topicCount',
'value' => 'topicCount',
],
'created_at',

['class' => 'yii\grid\ActionColumn','template' => '{view}',],
],
]); ?>

在我的 Controller /TagController.php 中:

public function actionIndex()
{
$dataProvider = new ActiveDataProvider([
'query' => Tag::find(),
'sort'=> [
'defaultOrder' => ['id'=>SORT_DESC],
'attributes' => ['id','topicCount'],
],
'pagination' => [
'pageSize' => 100,
],
]);

return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}

在我的模型/TagSearch.php 中:

<?php

namespace common\models;

use Yii;

/**
* This is the model class for table "tags".
*
* @property integer $id
* @property string $name
* @property string $created_at
* @property string $updated_at
*/
class TagSearch extends Tag
{

public $topicCount;

/**
* @inheritdoc
*/
public function rules()
{
return [
[['topicCount'], 'safe']
];
}

public function search($params)
{
// create ActiveQuery
$query = Tag::find();
$query->joinWith(['topicCount']);

$dataProvider = new ActiveDataProvider([
'query' => $query,
]);

$dataProvider->sort->attributes['topicCount'] = [
'asc' => ['topicCount' => SORT_ASC],
'desc' => ['topicCount' => SORT_DESC],
];

if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}

$query->andFilterWhere([
//... other searched attributes here
])
->andFilterWhere(['=', 'topicCount', $this->topicCount]);

return $dataProvider;
}


}

在索引 View 中我可以看到正确的 topicCount:

enter image description here

但是在单击 topicCount 列时出现错误:

异常“PDOException”,消息为“SQLSTATE[42703]:未定义的列:7 错误:列“topicCount”不存在
第 1 行:SELECT * FROM "tags"ORDER BY "topicCount"LIMIT 100

感谢任何指导......!


[编辑]

按照 Lucas 的建议,我在我的 $dataProvider 中设置了我的 dataProvider 查询,如下所示:

'query' => $query->select(['tags.*','(select count(topic_tags.id) from topic_tags where topic_tags.tag_id=tags.id) topicCount'])->groupBy('tags.id'),

我得到了错误:

异常“PDOException”,消息为“SQLSTATE[42P01]:未定义的表:7 错误:缺少表“标签”的 FROM 子句条目

所以我重新表述如下:

        'query' => $query->from('tags')->leftJoin('topic_tags','topic_tags.tag_id = tags.id')->select(['tags.*','(select count(topic_tags.id) from topic_tags where topic_tags.tag_id=tags.id) topicCount'])->groupBy('tags.id'),

现在我得到了结果:

enter image description here

显然没有设置 topicCount 列,所以当我尝试按它排序时,它返回错误:

异常“PDOException”,消息为“SQLSTATE[42703]:未定义的列:7 错误:列“topicCount”不存在

但是当我直接在数据库上尝试 SQL 时,它工作正常:

enter image description here

所以我想问题出在 Yii 处理别名“topicCount”的方式上?


第二次编辑

在 GridView 中没有设置 topicCount 的情况下,结果仍然相同。我在下面展示了我的 TagSearch 模型、TagController 和 View /标签/索引 View 文件:

标签搜索

<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Tag;

/**
* TagSearch represents the model behind the search form about `common\models\Tag`.
*/
class TagSearch extends Tag
{

public $topicCount;

/**
* @inheritdoc
*/
public function rules()
{
return [
[['id', 'topicCount'], 'integer'],
[['name', 'created_at', 'updated_at', 'topicCount'], 'safe'],
];
}

/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}

/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Tag::find();

$dataProvider = new ActiveDataProvider([
'query' => $query->from("tags")->select(["tags.*","(select count(topic_tags.id) from topic_tags where topic_tags.tag_id=tags.id) topicCount"])->groupBy("tags.id"),
]);

$this->load($params);

if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
$query->where('0=1');
return $dataProvider;
}

$query->andFilterWhere([
'id' => $this->id,
'topicCount' => $this->topicCount,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
]);

$query->andFilterWhere(['like', 'name', $this->name]);

return $dataProvider;
}
}

标签模型

<?php

namespace common\models;

use Yii;

/**
* This is the model class for table "tags".
*
* @property integer $id
* @property integer $topicCount
* @property string $name
* @property string $created_at
* @property string $updated_at
*/
class Tag extends \yii\db\ActiveRecord
{

public $topicCount;

/**
* @inheritdoc
*/
public static function tableName()
{
return 'tags';
}

/**
* @inheritdoc
*/
public function rules()
{
return [
[['topicCount'], 'integer'],
[['name'], 'string'],
[['created_at', 'updated_at'], 'required'],
[['created_at', 'updated_at'], 'safe']
];
}

/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'topicCount' => 'TC',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}

}

标签 Controller

public function actionIndex()
{

$searchModel = new TagSearch();
$myModels = $searchModel->search([]);

return $this->render('index', [
'dataProvider' => $myModels,
]);
}

标签/索引

<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
'topicCount',
'created_at',
'updated_at',
['class' => 'yii\grid\ActionColumn','template' => '{view}',],
],
]); ?>

我错过了什么?

最佳答案

所以解决了以下this wiki :

因为在我的例子中我不使用 SUM('amount'),所以我更改为以下并且工作完美:

标签模型:

public function getTopicCount() 
{
return $this->hasMany(TopicTag::className(), ["tag_id" => "id"])->count();

}

标签搜索模型:

    $query = Tag::find();
$subQuery = TopicTag::find()->select('tag_id, COUNT(tag_id) as topic_count')->groupBy('tag_id');
$query->leftJoin(["topicSum" => $subQuery], '"topicSum".tag_id = id');

刚遇到生成SQL的问题:

exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR:  missing FROM-clause entry for table "topicsum"

这可能是 Postgres 特有的问题,必须安排代码以便生成的 SQL 变成这样:

SELECT COUNT(*) FROM "tags" 
LEFT JOIN (SELECT "tag_id", COUNT(*) as topic_count FROM "topic_tags" GROUP BY "tag_id") "topicSum"
ON "topicSum".tag_id = id

注意 "topicSum".tag_id 部分中的双引号。

希望这对在 Yii2 上使用 Postgres 的人有所帮助。

关于php - Yii2:对 GridView 中的关系计数列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31782754/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com