Search code examples
cakephptranslatecontain

CakePHP 3.6 Translate and Contain


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').


Solution

  • 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.