2014-09-10 75 views
2

我正在阅读文档,似乎没有如何在CakePHP 3中使用beforeFind的示例。我想也许我可以像我在2中那样做,但那样做了不行。这是我做到的两种方式。CakePHP 3如何在表上添加beforeFind

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

我还没有使用3.x,但在以前的版本中,您仍然需要返回从/传入的'beforeFind()' – 2014-09-10 22:34:22

回答

-1

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

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