CakePHP 3`setEntityClass()`用于包含的表

时间:2018-07-30 12:39:59

标签: cakephp associations cakephp-3.0 model-associations contain

我有什么

  • CakePHP 3.6
  • PostsTable belongsTo AuthorsTable

我想要的

  1. 选择包含其作者的帖子
  2. 在一种特定情况下,为作者使用自定义实体

我尝试过的

用Google搜索了很多,找不到任何东西。必须即兴创作。

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

那很好。

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

这不起作用,因为contain()不接受表实例。

有人知道仅通过一次find()通话即可设置不同实体的方法吗?

1 个答案:

答案 0 :(得分:0)

它不起作用,因为contain()接受一个array | string | null,并且您试图将其传递给Table实例。将表名称传递给它,而不是用于水合作用:

// 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());