我正在處理多語言帖子。我在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()]);
}
但沒有運氣。誰能指導我?謝謝閱讀。
謝謝@ndm這有幫助 – Invincible