添加产品CakePHP时添加计数器

时间:2017-10-30 05:46:30

标签: php cakephp

在我的表类别中,我有一行名为count的行,我想在每次创建新产品时更新,但我是这个cakephp的新手,我不知道如何同时使用2个控制器。< / p>

它在我的产品控制器中添加:(默认添加创建与烘焙)

   public function add()
    {
        $product = $this->Products->newEntity();
        if ($this->request->is('post')) {
            $product = $this->Products->patchEntity($product, $this->request->getData());

            if ($this->Products->save($product)) {
                $this->Flash->success(__('The product has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The product could not be saved. Please, try again.'));
        }
        $categorys = $this->Products->Categorys->find('list', ['limit' => 200]);
        $this->set(compact('product', 'categorys'));
        $this->set('_serialize', ['product']);
    }

每个产品都有相关的类别。

1 个答案:

答案 0 :(得分:2)

查看Cookbook

中的CounterCache行为

您所要做的就是将它附加到您的模型并告诉它您要存储计数的列的名称(我假设这里称为product_count

class CategoriesTable extends Table
{
    public function initialize(array $config)
    {
        $this->addBehavior('CounterCache', [
            'Products' => ['product_count']
        ]);
    }
}