Inv*_*ble 1 entity exists cakephp-3.0
我正在处理多语言帖子。我在 PostsTable 中添加了 beforefind() 以便我可以列出当前语言的帖子
public function beforeFind(Event $event, Query $query) {
$query->where(['Posts.locale' => I18n::locale()]);
}
Run Code Online (Sandbox Code Playgroud)
为了允许用户以不同语言复制帖子,我编写了以下功能:
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]);
}
Run Code Online (Sandbox Code Playgroud)
为了检查帖子是否已经重复。我正在检查“编辑”功能:
$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);
Run Code Online (Sandbox Code Playgroud)
但由于 beforefind() 将查询附加到上述查询。我没有得到任何结果。有什么办法可以忽略 beforefind() 仅针对某些查询。我尝试使用实体如下:
public function beforeFind(Event $event, Query $query) {
if(isset($entity->duplicate)) {
return true;
}
$query->where(['Posts.locale' => I18n::locale()]);
}
Run Code Online (Sandbox Code Playgroud)
但没有运气。有人可以指导我吗?谢谢阅读。
有多种可能的方法来处理这个问题,一种是利用Query::applyOptions()设置一个选项,您可以在回调中检查
$query->applyOptions(['injectLocale' => false])
Run Code Online (Sandbox Code Playgroud)
public function beforeFind(Event $event, Query $query, ArrayObject $options)
{
if(!isset($options['injectLocale']) || $options['injectLocale'] !== false) {
$query->where(['Posts.locale' => I18n::locale()]);
}
}
Run Code Online (Sandbox Code Playgroud)
警告:$options参数当前作为数组传递,而它应该是ArrayObject( #5621 ) 的一个实例