realtebo
realtebo

Reputation: 25661

How sort CgridView using a 'count' columne

Situation: CausalType 1 -> N Causal

Into admin view for causaltype, i'm using cgridview, and I must show the number of causala of each causalType.

I setup the relation into CausalType

return array(
                        "causals" => array (self::HAS_MANY, "Causal", "causalTypeId"  ), 
                );

I added class variable

  public $activeCausalCount; 

and this is the column in admin view

 array (
                  'name' => 'activeCausalCount',
                  'value' => 'count($data->causals)',    
            ), 

Actually this is my criteria in search()

    $criteria=new CDbCriteria;

$criteria->compare('id',$this->id,true);
$criteria->compare('name',$this->name,true);
$criteria->compare('isActive',$this->isActive);

The count of causal of each type is correct, but I've some problem

1) I need to count only ACTIVE causals (count causals where causals.isActive = 1)

2) I need to sort the column

3) I need to filter (by integer)

Upvotes: 1

Views: 129

Answers (2)

SuVeRa
SuVeRa

Reputation: 2904

If you really need sorting and filtering on COUNT, then that can be little big process.

one way is...

Add a column to your CausalType table ( call it activeCausals )

define a relation in CausalType model

"totalActiveCasuals" => array(
      self::STAT, 
      "Causal", 
      "causalTypeId", 
      'condition'=>'totalActiveCasuals.isActive=1'
), 

and define afterSave method in Causal

protected function afterSave() 
{
    $this->causaltype->activeCausals = $this->causaltype->totalActiveCasuals;
    $this->causaltype->save();

    return parent::afterSave();
}

now you can filter, sort on new column activeCausals very very easily.

Upvotes: 2

Asgaroth
Asgaroth

Reputation: 4334

Add a new relation to your CasualType of type STAT like this:

return array(
   "casuals" => array (self::HAS_MANY, "Causal", "causalTypeId"  ), 
   "totalCasuals" => array (self::STAT, "Causal", "causalTypeId"  ), 
   "totalActiveCasuals" => array (self::STAT, "Causal", "causalTypeId", 'condition' => 'active = true'    ), 
);

then in your view just use it as a normal attribute/relation

Upvotes: 0

Related Questions