Yii2:在GridView中对关系计数列进行排序

时间:2015-08-03 08:32:17

标签: php gridview yii2

[编辑2]

我很难按主题排序'它被定义为模型上的关系getter' Tag'。 主题可以包含大量标记,并希望按标记的多少主题对标记进行排序。

在我的模型/ Tag.php中:

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

在我的观点/ tag / index.php中:

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

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

在我的控制器/ 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;
}


}

在索引视图中,我可以看到正确的topicCount:

enter image description here

但是点击topicCount列我得到错误:

exception 'PDOException' with message 'SQLSTATE[42703]: Undefined column: 7 ERROR: column "topicCount" does not exist LINE 1: SELECT * FROM "tags" ORDER BY "topicCount" LIMIT 100

感谢任何指导..!

[编辑]

跟随卢卡斯&#39;建议,我在我的$ 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'),

我收到了错误:

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

所以我重新拟定了这样的话:

        '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列,所以当我尝试按它排序时,它会返回错误:

exception 'PDOException' with message 'SQLSTATE[42703]: Undefined column: 7 ERROR: column "topicCount" does not exist

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

enter image description here

所以我认为问题在于Yii处理别名&#39; topicCount&#39;?

第二次编辑

如果没有在Grid视图中设置topicCount,结果仍然相同。 我在下面显示我的TagSearch模型,TagController和views / tag / index视图文件:

TagSearch

<?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',
        ];
    }

}

TagController

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}',],
    ],
]); ?>

我错过了什么?

4 个答案:

答案 0 :(得分:4)

this wiki后解决:

因为在我的情况下我不使用SUM(&#39;金额&#39;),所以我改为以下并完美运作:

标记模型:

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

}

TagSearch模型:

    $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的人有所帮助。

答案 1 :(得分:1)

您应该将查询更改为分组并选择计数而不是使用关系。

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

这将在查询中添加topicCount作为结果对象,这将使其行为像普通列一样。

另外作为旁注,对于在Yii2中处理关系的方法,它必须返回ActiveQuery个对象。您的getTopicCount()将计数作为int而不是查询返回,因此Yii2不会将其视为关系。

答案 2 :(得分:0)

基于this Wiki和@ arogachev的回答。我将select属性设置为获取标记计数

public function search($params)
{ 
$query = SomeModels::find()
         ->select('subQueryName.field_count, someModels.*');
// ....

因此它会像这样SELECT subQuery.field_count, someModels.* ...

给出SQL

在视图(网格),

[
  'attribute'=> 'field_count',
],

谢谢@arogachev,你救了我:)。

答案 3 :(得分:0)

轻量级解决方案只是在PostgreSQL中重新view

并使用gii生成器生成模型,使用模型和顺序&amp;找工作。

更新&amp;删除使用table模型进行搜索&amp; index使用view模型。

例如

行动update&amp; delete使用Tag模型

行动index&amp; view使用TagView模型。