我有一个包含所有条目的表格,包括多种语言的所有翻译:如何在翻译字段上创建分页排序链接?(蛋糕3.1.6)
摘要:这不起作用,我无法以这种方式对翻译进行排序:
$this->Paginator->sort('_translations.es.title', 'Spanish')
长版:
| Title ENGLISH | Title SPANISH | Title GERMAN | = pagination sort links
| ---------------- | ---------------- | --------------- |
| Christmas | Navidad | Weihnachten |
| Spring | Primavera | Frühling |
| ...
所以这是我的简化测试设置:
表格文章只有一个title
需要翻译的字段。
i18n表是本书中描述的默认设置。
烘焙表类/src/Model/Table/ArticlesTable.php
,添加翻译行为:
public function initialize(array $config) {
// ... default config (removed in this post to simplify code)
$this->addBehavior('Translate', ['fields' => ['title']]); // added this line
}
烘焙实体类/src/Model/Entity/Article.php
,添加TranslateTrait:
namespace App\Model\Entity;
use Cake\ORM\Behavior\Translate\TranslateTrait; // added this line
use Cake\ORM\Entity;
class Article extends Entity {
protected $_accessible = [
'*' => true,
'id' => false,
];
use TranslateTrait; // added this line
}
烘焙控制器 /src/Controller/ArticlesController.php
,修改如下:
namespace App\Controller;
use App\Controller\AppController;
class ArticlesController extends AppController {
public $paginate = [
'sortWhitelist' => [ // Allow pagination sort on this fields:
'title',
'_translations.es.title',
'_translations.de.title'
]
];
public function index() {
$query = $this->Articles->find('translations'); // Retrieve All Translations
$this->set('articles', $this->paginate($query));
}
}
烘焙视图 /src/Template/Articles/index.ctp
,修改/简化:
<table>
<tr>
<th><?= $this->Paginator->sort('title', 'English') ?></th>
<th><?= $this->Paginator->sort('_translations.es.title', 'Spanish') ?></th>
<th><?= $this->Paginator->sort('_translations.de.title', 'German') ?></th>
</tr>
<?php foreach ($articles as $article): ?>
<tr>
<td><?= h($article->title) ?></td>
<td><?= h($article->_translations['es']->title) ?></td>
<td><?= h($article->_translations['de']->title) ?></td>
</tr>
<?php endforeach; ?>
</table>
表中的翻译显示正确,但无法按翻译字段排序。当我单击翻译的分页链接时,出现以下错误:
SQLSTATE [42S22]:未找到列:1054 未知列“_translations.es”在“订单子句”中
SQL Query:
SELECT Articles.id AS `Articles__id`,
Articles.title AS `Articles__title`,
Articles.created AS `Articles__created`,
Articles.modified AS `Articles__modified`
FROM articles Articles
ORDER BY _translations.es asc LIMIT 20 OFFSET 0
在这个类似的问题中,使用了格式Posts_title_translation.content
- 我不知道这是从哪里来的,但我也尝试过这种方式(当然我还在分页器白名单中添加了字段名称的变体):
$this->Paginator->sort('Articles_title_translation', 'Spanish')
$this->Paginator->sort('Articles_title_translation.es', 'Spanish')
$this->Paginator->sort('Articles_title_translation.content', 'Spanish')
$this->Paginator->sort('Articles_title_translation.es.content', 'Spanish')
他们都没有工作......(显然)
如何按标题字段的 i18n 翻译对表格项目进行排序?