2012-02-17 35 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