Model Relation: Count

Hi folks!

I want to count items from a related table within a model.

There are 3 Tables:

  • TableA (This model)

  • TableB

  • TableC (Count these entries)

These tables are related with the primary key from Table B (TableBid).

This relation normally looks like that:




class TableA extends CActiveRecord

{

    public function relations()

    {

        return array(

            'tableB' => array(self::BELONGS_TO, 'TableB', 'TableBid'),

            'tableC' => array(

                self::HAS_MANY,

                'TableC',

                array('TableBid' => 'TableBid'),

                'through' => 'tableB'

            ),

        ),

    }

}



So far so good.

When I change self::HAS_MANY -> self::STAT to count the items:




'tableCcount' => array(

    self::STAT,

    'TableC',

    array('TableBid' => 'TableBid'),

    'through' => 'tableB'

),



then I get the Yii error which seems to be related to this Issue:




Eigenschaft "CStatRelation.through ist nicht definiert.



So I tried to replace the unsupported "through" with a "join":




'tableCcount' => array(

    self::STAT,

    'TableB',

    array('TableBid' => 'TableBid'),

    'join' => 'LEFT JOIN TableC tc ON tc.TableBid = t.TableBid'

),



But self::STAT does not support the use of specific keys (Issue):




 preg_match() expects parameter 2 to be string, array given

/framework/db/ar/CActiveFinder.php(1391)



Can anybody help me to find a workaround or even a fix for the two YII issues?

Thanks alot!

Solved it with a workaround:

New column TableA.COUNT_C which is updated by afterSave() and afterDelete() in TableC Model




class TableC extends ActiveRecord

{

	protected function afterSave()

	{

		parent::afterSave();


		// Update TableA.COUNT_C

		// In my case, only update update COUNT_C on new records because entries from TableC ever stay related to the same TableA entry

		if ($this->isNewRecord) {

			$TableAID = $this->TableAID;

			$TableA = Geschaeftsfall::model()->findByPk($TableAID);

			$TableA->COUNT_C++;

			$TableA->save();

		}

	}


	protected function afterDelete()

	{

		parent::afterDelete();


		// Update TableA.COUNT_C

		$TableAID= $this->TableAID;

		$TableA = TableA::model()->findByPk($TableAID);

		if ($TableA->COUNT_C > 0) { // Avoid negative values... Just to be shure

			$gf->COUNT_C--;

			$gf->save();

		}

	}

// ....

}