I have the following query that is becoming long and clunky, and need to refactor this into a ‘Yii style’ way of doing things… the query is quite mammouth in my view and I want to try to minismise & make it ‘cleaner’ with Yii CDbCriteria if possible…
Any advice would be appreciated :
return ShopProducts::model()->findAllByAttributes(array(
'organisation_id' => $this->organisation_id,
),
'IF(
availability=3,
(SELECT count(*) FROM shop_product_years WHERE shop_product_years.Guid = t.Guid AND shop_product_years.year_id = '.Myuser::model()->currentUser->year_id.') > 0,
(availability=:availability OR availability = '.ShopProducts::ALL.')
)
AND (multi_buy = 1
OR (multi_buy = 0
AND (
SELECT count(*)
FROM shop_purchases
WHERE shop_purchases.user_id = '.Yii::app()->user->id.'
AND shop_purchases.GUID = t.Guid
) = 0
AND (
SELECT count(*)
FROM shop_purchases_queue
WHERE shop_purchases_queue.user_id = '.Yii::app()->user->id.'
AND shop_purchases_queue.GUID = t.Guid
) = 0
OR (
SELECT count(*)
FROM shop_purchases
WHERE shop_purchases.user_id = '.Yii::app()->user->id.'
AND shop_purchases.GUID = t.Guid
AND shop_purchases.refunded IS NULL
) = 0
)
)
/* Classroom */
OR (
SELECT count(*)
FROM shop_product_classrooms
WHERE
shop_product_classrooms.Guid = t.Guid
AND shop_product_classrooms.classroom_id IN ( '. $user_classroom_ids .' )
)
AND active='.ShopProducts::ACTIVE.'
AND product_type_id='.ShopProducts::SCHOOL_PRODUCT_TYPE_ID,
array(
':availability' => (Myuser::model()->currentUser->organisation->secondary_start_year === 0) ? '('.ShopProducts::SECONDARY_ONLY.' OR '.ShopProducts::PRIMARY_ONLY.')' : ((Myuser::model()->currentUser->isSecondary) ? ShopProducts::SECONDARY_ONLY : ShopProducts::PRIMARY_ONLY)
));