2012-02-17 85 views
1

我有一個「優惠券」控制器。索引()函數抓住每個類別中的優惠券的少數,並顯示它們(即):CakePHP:保持「視圖」數

public function index() { 
    $showPerPage = 4; 

    $this->Coupon->recursive = 0; 

    $this->set('restaurants', $this->Coupon->findAllBycategory_id('1', '', '', $showPerPage)); 
    $this->set('entertainment', $this->Coupon->findAllBycategory_id('2', '', '', $showPerPage)); 
    $this->set('spas', $this->Coupon->findAllBycategory_id('3', '', '', $showPerPage)); 
    $this->set('services', $this->Coupon->findAllBycategory_id('4', '', '', $showPerPage)); 
    $this->set('hotels', $this->Coupon->findAllBycategory_id('5', '', '', $showPerPage)); 
    $this->set('retail', $this->Coupon->findAllBycategory_id('6', '', '', $showPerPage)); 
} 

對於每個陣列組(餐館,entertinamnent,溫泉等),我要通過每個優惠券以過濾並將它們的「mini_views」計數器增加到1.我在模型中創建了一個名爲「increaseMiniView($ id)」的函數。處理這個問題的最好方法是什麼?我知道我可以通過每一個foreach,但我不知道是否有更好的方法(我也可以把代碼放在視圖中,但我知道這是最好的方式)

回答

1

我認爲你可以做這樣的事情:

$restaurants = $this->Coupon->findAllBycategory_id('1', '', '', $showPerPage); 
foreach($restaurants['Coupon'] as $restaurant) 
    $couponId[] = $restaurant['id']; 

$entertainments = $this->Coupon->findAllBycategory_id('2', '', '', $showPerPage); 
foreach($entertainments['Coupon'] as $entertainment) 
    $couponId[] = $entertainment['id'];  

// ... repeat for all queries 

$this->Coupon->updateAll(
    array('Coupon.count' => 'Coupon.count+1'), 
    array('Coupon.id' => $couponId) 
); 

$this->set(compact('restaurants', 'entertainments')); 

Complex Find ConditionsupdateAll

將所有優惠券ID存儲在數組中,並將它們傳遞給updateAll方法,您可以在其中更新所需的任何字段。

祝你好運!

+1

沒問題。您也可以將循環委派給'Set :: extract'。 – bfavaretto 2012-02-18 00:54:53