Cakephp Error: The Images association is not defined on Projects

Cakephp Error: The Images association is not defined on Projects

我有一个带有 "ProjectsManager" 插件的 CakePHP 应用程序。

src/Model/Table/ImagesTable.php:

public function initialize(array $config)
{
    ...
    $this->belongsToMany('ProjectsManager.Projects', [
        'className' => 'ProjectsManager.Projects',
        'foreignKey' => 'image_id',
        'targetForeignKey' => 'project_id',
        'joinTable' => 'images_projects'
    ]);

plugins/ProjectsManager/src/Model/ProjectsTable.php:

public function initialize(array $config)
{
    ...
    $this->hasMany('Images', [
        'className' => 'Images',
        'foreignKey' => 'project_id',
        'targetForeignKey' => 'image_id',
        'joinTable' => 'images_projects'
    ]);
    $this->hasOne('CoverImage', [
        'className' => 'Images',
        'bindingKey' => 'cover',
        'foreignKey' => 'id'
    ]);

plugins/ProjectsManager/src/Controller/Publica/ProjectsController.php:

    $this->paginate = [
        'fields' => ['Projects.title', 'Projects.slug', 'Projects.cover'],
        'conditions' => $where,
        'contain' => ['Images','CoverImage' => ['fields' => ['filename']]],
        'limit' => 15,
        'order' => ['id' => 'desc']
   ];

因此,在我的控制器中,我想加载所有项目和关联的图像,请查看上面的代码。 运行 这给了我一个错误:

The Images association is not defined on Projects.

所以我一直在搜索和阅读,发现我需要为插件添加前缀才能使其正常工作。所以我做了代码中可以看到的。但是错误仍然存​​在。

有什么想法吗?

经过一番尝试,我找到了解决方案。

在应用程序控制器中(例如 ImagesController.php),当您使用 $this->Images->... 时它会起作用。使用该代码,将调用 ImagesModel。

在插件内部,这不起作用...或者至少没有调用 ProjectsModel。

所以我需要通过将以下代码添加到 ProjectsController.php:

来手动加载模型
public function initialize()
{
    parent::initialize();
    $this->loadModel('ProjectsManager.Projects');
}