CakePHP 3.x动态查找器方法

时间:2015-04-08 16:10:02

标签: cakephp-3.0

我在CakePHP 3应用程序中遇到此问题 我试图通过它的slug和属于该类别的所有相关文章获得一个类别。 我在Controller中使用动态查找器方法findBySlug,但它在视图中抛出错误。

这是我的代码:

public function view($slug = null)
{
    if (!$slug) {
        throw new NotFoundException(__('Invalid category slug'));
    }

    $category = $this->Categories->findBySlug($slug, [
        'contain' => [
            'Articles'
        ]
    ]);

    $this->set(compact('category'));
}

和视图:

<div class="categories view">

<h2><?= h($category->name); ?></h2>

<?php foreach ($category->articles as $article): ?>
    <?php echo $article->title; ?>
<?php endforeach; ?>

有人可以提供或指出我的解决方案吗?

提前谢谢

这是我在控制器中获得的调试:

object(App\Model\Entity\Category) {

'new' => false,
'accessible' => [
    'name' => true,
    'slug' => true,
    'articles' => true
],
'properties' => [
    'id' => (int) 2,
    'name' => 'International',
    'slug' => 'international.html'
],
'dirty' => [],
'original' => [],
'virtual' => [],
'errors' => [],
'repository' => 'Categories'

}

以下是我的模特:

class CategoriesTable扩展了Table {     public function initialize(array $ config)     {         $这 - &GT; addBehavior给( '时间戳');

    $this->displayField('name');

    $this->hasMany('Articles', [
        'className' => 'Articles',
        'foreignKey' => 'category_id',
        'conditions' => [
            'published' => 1
        ],
        'dependent' => true
    ]);
}

}

类ArticlesTable扩展了Table {     public function initialize(array $ config)     {         $这 - &GT; addBehavior给( '时间戳');

    $this->belongsTo('Users');

    $this->belongsTo('Categories', [
        'foreignKey' => 'category_id'
    ]);
}

}

1 个答案:

答案 0 :(得分:0)

find()方法将始终返回Query个对象。在尝试从中获取属性之前,您需要获取至少一个结果:

$thisIsAQuery = $this->Categories->findBySlug($slug)->contain(['Articles'])
// I can now fetch the category
$category = $thisIsAQuery->first();


// And now I can get the category name
echo $category->name