我正在处理多语言帖子。我在PostsTable中添加了beforefind(),因此我可以列出当前语言的帖子
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()只用于cerrtain查询。我尝试使用如下实体:
public function beforeFind(Event $event, Query $query) {
if(isset($entity->duplicate)) {
return true;
}
$query->where(['Posts.locale' => I18n::locale()]);
}
但没有运气。谁能指导我?谢谢阅读。
答案 0 :(得分:4)
有多种方法可以解决这个问题,一种方法是利用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)的实例
答案 1 :(得分:1)
$this->Model->find('all', array(
'conditions' => array(...),
'order' => array(...),
'callbacks' => false
));