【问题标题】:CakePHP 3.6 Translate and ContainCakePHP 3.6 翻译和包含
【发布时间】:2019-02-01 17:48:31
【问题描述】:

我需要从显示所有翻译的记录中构建一个视图,并且我还想将显示来自关联模型的附加记录的表添加到该特定记录。相关模型无需翻译,只需以当前语言显示即可。 有没有办法将 'Contain' 与 ->find('translations')-> 结合起来? 或者这样做的最佳做法是什么?

f.e.一个组有许多角色。因此,我想向该组展示 Groups.name 的所有翻译以及属于该组的所有角色的列表。

现在我用单独的发现做到了:

public function view($id = null)
{
    $group = $this->Groups->find('translations')->where(['Groups.id' => $id])->first();
    $this->set('group', $group);
    // related Roles
    $related_roles = $this->Groups->Roles->find('all', [
        'conditions' => ['Roles.group_id' => $id]
    ]);
    $this->set('related_roles', $related_roles);
}

但我想知道是否不可能将其结合到 1 个查找中,是否有可能将某种包含 () 与 find('translations') 一起使用。

【问题讨论】:

  • 您可能需要添加更多详细信息,说明您想要实现的具体目标(例如现有数据和结果数据的示例),以及您面临的具体问题是什么.
  • 我假设您在第一个查询中使用contain() 时遇到了问题?我仍然不确定你想要的结果是什么,从最初的声明来看你希望容器不被翻译,但更新读起来好像你可能也希望检索容器被翻译?
  • 只有主记录(在截图中'Administrators'组需要有所有翻译。相关记录只能以1种语言显示(选择的语言。所以你可以看到上面的代码有效)好吧,我只想知道是否有更好的 (Cake-) 方法来做到这一点。简而言之:你能将 contains() 与 find('translations') 一起使用吗?
  • 可以,你试过了吗?
  • 是的,我试过了,但没用。你能告诉我如何为上午代码编写它吗?

标签: cakephp translate contain


【解决方案1】:

我们已经通过使用这个解决了这个问题,可能会有所帮助

为翻译创建一个单独的表,即 groups_i18n https://book.cakephp.org/3.0/en/orm/behaviors/translate.html#using-a-separate-translations-table

现在在 Entity/Group.php 中添加行

protected $_accessible = [
    //other columns
    'name_translation' => true,
    '_i18n' => true,
    '_translations' => true
];

现在在 GroupsTable.php 中,添加行为

$this->addBehavior('Translate', [
        'fields' => ['name'],
        'translationTable' => 'GroupsI18n'
    ]);

现在在 GroupsController.php 中

$group = $this->Groups->get($id, [
        'contain' => ['Roles', 'Groups_name_translation', 'GroupsI18n']
    ]);

【讨论】:

    【解决方案2】:

    我是这样解决的:

    $group = $this->Groups
                ->find('translations')
                ->where(['Groups.id' => $id])
                ->contain(['Roles', 'Users'])
                ->first();
    

    在我尝试之前是这样的手册:

    $group = $this->Groups
                ->find('translations')
                ->where(['Groups.id' => $id])
                ->first();
    $group->contain(['Roles', 'Users']);
    

    但无论出于何种原因,这对我不起作用。

    【讨论】:

      猜你喜欢
      • 2019-01-04
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 2012-10-10
      • 1970-01-01
      相关资源
      最近更新 更多