在CakePHP v3中使用slug



我计划将我的CakePHP v2升级到v3网站。所以我开始学习通过看博客教程& &;

接下来,我开始根据我的CakePHP v2站点进行定制。

我想做的第一件事是在URL中使用插入符而不是id。我在数据库中添加了段塞列。

但我总是得到一个错误,当我点击url与slug。错误是

通知(8):未定义属性:CakeORMQuery::$created [APP/Template/Articles/view.>Ctp,第3行]

感谢您的帮助。

这是我的路线

$routes->connect('/', ['controller' => 'Articles', 'action' => 'index']);
$routes->connect('/articles/:slug', ['controller' => 'Articles', 'action' => 'view'], ['pass' => ['slug']]);

这是我的控制器

public function index()
{
     $this->set('articles', $this->Articles->find('all'));
}

public function view($slug = null)
{
    $article = $this->Articles->findBySlug($slug);
    $this->set(compact('article'));
}

这是我的索引。

<h1>Blog articles</h1>
<table>
<tr>
    <th>Id</th>
    <th>Title</th>
    <th>Created</th>
    <th>Slug</th>
</tr>
<?php foreach ($articles as $article): ?>
<tr>
    <td><?= $article->id ?></td>
    <td>
        <?= $this->Html->link($article->title, ['action' => 'view', $article->slug]) ?>
    </td>
    <td>
        <?= $article->created ?>
    </td>
    <td>
        <?= $article->slug ?>
    </td>
</tr>
<?php endforeach; ?>

find()方法返回一个查询对象。由于需要匹配该段代码的单个实体,因此在查询对象上调用first():

$article = $this->Articles->findBySlug($slug)->first();

最新更新