2015-01-09 38 views
1

我正在處理多語言帖子。我在PostsTable加入beforefind(),所以我可以列出職位,當前語言Cakephp 3:如何在查詢特定查詢之前忽略?

public function beforeFind(Event $event, Query $query) { 

    $query->where(['Posts.locale' => I18n::locale()]); 
} 

爲了讓用戶重複使用不同語言的帖子我寫了以下功能:

public function duplicate(){ 
    $this->autoRender = false; 
    $post_id= $this->request->data['post_id']; 

    $post = $this->Posts 
      ->findById($post_id) 
      ->select(['website_id', 'category_id', 'locale', 'title', 'slug', 'body', 'image', 'thumb', 'meta_title', 'meta_description', 'other_meta_tags', 'status']) 
      ->first() 
      ->toArray(); 

    foreach($this->request->data['site'] as $site) { 
     if($site['name'] == false) { 
      continue; 
     } 
     $data = array_merge($post, [ 
      'website_id' => $site['website_id'], 
      'locale' => $site['locale'], 
      'status' => 'Draft', 
      'duplicate' => true 
     ]); 


     $pageData = $this->Posts->newEntity($data); 

     if($this->Posts->save($pageData)) { 
      $this->Flash->success(__('Post have been created.'));; 
     } else{ 
      $this->Flash->error(__('Post is not created.')); 
     } 

    } 

    return $this->redirect(['action' => 'edit', $post_id]); 
} 

爲了檢查如果帖子已經重複。我在「編輯」 functino做了檢查:

$languages = TableRegistry::get('Websites')->find('languages'); 

    foreach($languages as $language) 
    { 
     $exists[] = $this->Posts 
        ->findByTitleAndWebsiteId($post['title'], $language['website_id']) 
        ->select(['locale', 'title', 'website_id']) 
        ->first(); 
    } 
    $this->set('exists',$exists); 

但隨着beforefind()被追加查詢到上述查詢。我沒有得到任何結果。有沒有什麼辦法可以在beforeFind()之前忽略只有某些查詢。我嘗試使用實體如下:

public function beforeFind(Event $event, Query $query) { 

    if(isset($entity->duplicate)) { 
     return true; 
    } 
    $query->where(['Posts.locale' => I18n::locale()]); 
} 

但沒有運氣。誰能指導我?謝謝閱讀。

回答

3

有多種可能的方式來處理這個問題,一個是要利用Query::applyOptions()設置一個選項,你可以在你的回調檢查

$query->applyOptions(['injectLocale' => false]) 
public function beforeFind(Event $event, Query $query, ArrayObject $options) 
{ 
    if(!isset($options['injectLocale']) || $options['injectLocale'] !== false) { 
     $query->where(['Posts.locale' => I18n::locale()]); 
    } 
} 

警告:該$options說法是目前作爲數組傳遞,而它應該是一個實例ArrayObject#5621

+0

謝謝@ndm這有幫助 – Invincible

0

Callback methods可以使用這個忽略:

$this->Model->find('all', array(
    'conditions' => array(...), 
    'order' => array(...), 
    'callbacks' => false 
)); 
+0

謝謝先生felix :)我會試試這個。 – Invincible