CakePHP 3.6 Translate and Contain

250 views Asked by At

I need to build a view from a record showing all translations and I also want to add tables showing the attached records from associated models to that specific record. The associated models don't need to be translated they can just be shown in the current language. Is there a way to combine 'Contain' with ->find('translations')->? Or what would be the best practice to do this?

f.e. a Group has many Roles. So I want to show the group with all the translations for the Groups.name and also a list of all Roles belonging to this Group. enter image description here

Now I did it with separate finds:

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);
}

But I wonder if it's not possible to combine this in 1 find, if there is a possibility to use some kind of contain() with find('translations').

2

There are 2 answers

0
Lucky On BEST ANSWER

I solved it like this:

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

Before I tried is as in the manual like this:

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

But for whatever reason that wasn't working for me.

0
Ved On

We have solved this problem by using this, may be this can help

Create a separate table for translations i.e, groups_i18n https://book.cakephp.org/3.0/en/orm/behaviors/translate.html#using-a-separate-translations-table

now in add lines in Entity/Group.php

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

now in GroupsTable.php, add behavior

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

now in GroupsController.php

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