2014-09-10 65 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()