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

时间:2019-06-27 16:55:50

标签: cakephp-3.7

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

在我的子类别页面中,我需要加载相关的paquet,并且根据我的debug-kit工具栏,变量已正确加载。问题是视图显示了“未定义的属性”错误代码。我确定我缺少了一些东西,但我无法完全解决问题。

我的模特:

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]

1 个答案:

答案 0 :(得分:0)

您永远不会在生成的查询上调用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