Cakephp 3如何在表上添加beforeFind

时间:2014-09-10 22:32:37

标签: cakephp cakephp-3.0

我正在阅读文档,似乎没有关于如何在Cakephp 3中使用beforeFind的示例。我想也许我可以像我在2中那样做,但那不起作用。以下是我做的两种方式。

public function beforeFind(Event $event, Query $query, array $options, $primary){
        $primary = (bool) $primary;
        if(!empty($options['pure'])) {
            $query->hydrate(false)
                ->join([
                    'table' => 'main_'.$this->store_id,
                    'alias' => 'c',
                    'type' => 'LEFT',
                    'conditions' => 'c.id = Stores.MAIN_ID',
                ]);
        }
    }

第二种方式:

public function initialize(array $config) {
        if(!isset($config['store_id'])) throw new Exception('You must provide a store id');
        $this->store_id = $config['store_id'];
        $this->entityClass('P1\Model\Entity\Store');
        $this->eventManager()->attach([$this,'addMain'],'beforeFind');
    }
    public function addMain(Event $event, Query $query, array $options, $primary){
        $primary = (bool) $primary;
        if(!empty($options['pure'])) {
            $query->hydrate(false)
                ->join([
                    'table' => 'main_'.$this->store_id,
                    'alias' => 'c',
                    'type' => 'LEFT',
                    'conditions' => 'c.id = Stores.MAIN_ID',
                ]);
        }
    }

我做错了什么?

1 个答案:

答案 0 :(得分:-1)

您必须使用Query类中的方法applyOptions。

$this->Posts->find()->applyOptions(['pure'=>true])->all()