0

I have a poll in my project.In grid I have show the count.

echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
    ['class' => 'yii\grid\SerialColumn'],
    [
        'label' =>"Constituency",
        'attribute' => 'constituency',
        'value'=>function($data){
            return $data["constituency"];
        }
    ],
    [
        'class' => 'yii\grid\DataColumn',
        'label' =>"Count",
        'attribute' => 'count',
       'value'=>function($data){
            return $data->getCount($data["constituency"]);
        },
        'enableSorting'=>TRUE ,

    ],

],      

My Model
for get count

    public static  function  getCount($constituency){
    $cat = Polls::find()->where(['poll_place'=>$constituency])->count();
    // $cat = ArrayHelper::map($cat, 'id', 'name');
    return $cat;
}

The count column is a custom column.
Can anyone help to sort that column.
I have tried This and this.
Both are failed because my count attribute is not in my DB.
Showing the following error
Database Error

4
  • I can help you here but need some more information. Can you please show the code for getCount()? Commented Apr 5, 2018 at 13:54
  • What do you wish to get the count of, exactly? Commented Apr 5, 2018 at 13:59
  • update your question and add the code related to count .. model or searchModel .. Commented Apr 5, 2018 at 16:52
  • i have updated the question... Commented Apr 6, 2018 at 6:06

1 Answer 1

0

Sorting is done at SQL level, you cannot blindly allow sorting on virtual attribute, you need to adapt your query to handle such sorting.

First, you need to add proper relation between two models. In your Constituency model add something like:

public function getPools()
{
    return $this->hasMany(Pools::className(), ['pool_place' => 'constituency']);
}

Then join two tables in query and enable grouping, so you can be able to calculate count for each Constituency.

$query = Constituency::find()->joinWith('pools')->groupBy('constituency');

Then configure sorting:

$sort = new Sort([
    'attributes' => [
        'constituency',
        'count' => [
            'asc' => 'COUNT(pools.poll_place) ASC',
            'desc' => 'COUNT(pools.poll_place) DESC',
        ],
    ],
]);

You may also create count attribute in your Constituency and add ->addSelect(['count' => Expression('COUNT(pools.poll_place)')]) to your query, to avoid excessive queries for polls count for each Constituency.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.