1
votes

I have this problem with a CakePHP 3 application I am trying to get a category by it's slug and all related articles belonging to that category. I am using dynamic finder method findBySlug in the Controller but it throws an error in the view.

Here is my code:

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

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

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

and the view:

<div class="categories view">

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

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

Can anyone please provide or point me to a solution ?

Thank you in advance

And this is the debug I am getting in the controller:

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'

}

and here are my models:

class CategoriesTable extends Table { public function initialize(array $config) { $this->addBehavior('Timestamp');

    $this->displayField('name');

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

}

class ArticlesTable extends Table { public function initialize(array $config) { $this->addBehavior('Timestamp');

    $this->belongsTo('Users');

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

}

1
What error does it throw? Could you post it?AKKAweb
Notice (8): Undefined property: Cake\ORM\Query::$name [APP/Template/Categories/view.ctp, line 3]dkourk
Notice (8): Undefined property: Cake\ORM\Query::$articles [APP/Template/Categories/view.ctp, line 5] Warning (2): Invalid argument supplied for foreach() [APP/Template/Categories/view.ctp, line 5]dkourk
Well.. it looks like what you are returning cannot be pulled like that ($category->name). In your finder try to add ->first(); and see if that helps... so basically ])->first();AKKAweb
if it doesn't work, leave ->first() in place and add debug($category) right after it and post the content debug will print to you screen, here.AKKAweb

1 Answers

0
votes

the find() method will always return a Query object. You need to fetch at least one result before trying to get properties from it:

$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