控制器 HABTM 变量未加载到视图中

Controller HABTM variables not loading in view

我在 HasAndBelongsToMany 关联中有两个相关模型:Subcategoria 有很多 Paquetes,Paquete 有很多 Subcategorias。

在我的子类别页面中,我需要加载相关的 paquete,根据我的调试工具栏,变量正在正确加载。问题是视图向我显示 "undefined property" 错误代码。我确定我遗漏了什么,但我不太明白问题出在哪里。

我的模特:

class SubcategoriasTable extends Table
{

    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('subcategorias');
        $this->setDisplayField('title');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

    $this->belongsTo('Categorias', [
            'foreignKey' => 'categoria_id',
            'joinType' => 'INNER'
        ]);

    $this->belongsToMany('Paquetes');
    }
}

class PaquetesTable extends Table
{

    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('paquetes');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsToMany('Subcategorias', [
            'foreignKey' => 'paquete_id',
            'targetForeignKey' => 'subcategoria_id',
            'joinTable' => 'paquetes_subcategorias',
        'dependant' => false
        ]);
    }
}

我遇到问题的控制器:

namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\Query;

class SubcategoriasController extends AppController
{

    public function content($slug = null)
    {
    $subcategory = $this->Subcategorias
            ->findBySlug($slug)
            ->select(['title', 'id'])
            ->contain('Paquetes', function (Query $q) {
                return $q
                    ->select(['name', 'slug','cost','currency'])
                    ->where(['Paquetes.status' => true]);
            });

    $this->set(compact('subcategory',$subcategory));
    }
}

对应的视图模板(content.ctp):

<?php
    $subcategoryName = $subcategory->title;
    $title = $subcategoryName;
    $this->assign('title', $title); 
?>

<h1><?= $title ?></h1>
<?php foreach($subcategory->paquetes as $paquete) : ?>
    <!-- Each Paquete's loaded fields. -->
<?php endforeach; ?>

到目前为止,我收到以下错误消息:

Notice (8): Undefined property: Cake\ORM\Query::$title [APP/Template\Subcategorias\content.ctp, line 2]

您永远不会对您构建的查询调用 first()firstOrFail(),因此在您看来 $subcategory 仍然只是一个查询对象,而不是一个实体。

你的意思可能是:

$subcategory = $this->Subcategorias
    ->findBySlug($slug)
    ->select(['title', 'id'])
    ->contain('Paquetes', function (Query $q) {
        return $q
            ->select(['name', 'slug','cost','currency'])
            ->where(['Paquetes.status' => true]);
    })
->firstOrFail(); // This is the line that fetches the result and marshals it into an Subcategorias Entity