dkourk
dkourk

Reputation: 53

CakePHP 3.x dynamic finder method

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'
    ]);
}

}

Upvotes: 1

Views: 3993

Answers (1)

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

Upvotes: 0

Related Questions