CakePHP 3 `setEntityClass()` for a contained table

89 views Asked by At

What I have

  • CakePHP 3.6
  • PostsTable belongsTo AuthorsTable

What I want

  1. Select posts containing their authors
  2. In one specific case, use a custom entity for authors

What I've tried

Googled a lot, couldn't find anything. Had to improvise.

// in my controller action:
// set custom class for authors
$authorsTable->setEntityClass('App\Model\Entity\AuthorCustom');
// get authors
$results = $authorsTable->find('all');

That works fine.

// in my controller action:
// set custom class for authors
$authorsTable->setEntityClass('App\Model\Entity\AuthorCustom');
// get products including categories
$results = $postsTable->find('all')->contain($authorsTable);

That doesn't work because contain() doesn't accept a table instance.

Does anyone know a way to set a different entity on just one find() call?

1

There are 1 answers

0
Derek Fulginiti On

It doesn't work because contain() accepts an array|string|null and you are trying to pass it a Table instance. Pass it the table name instead used for hydration:

// in my controller action:
// set custom class for authors
$authorsTable->setEntityClass('App\Model\Entity\AuthorCustom');
// get products including categories
$results = $postsTable->find('all')->contain($authorsTable->getTable());