使用帖子标题作为url的CakePHP视图方法
我的投资组合有以下链接结构:使用帖子标题作为url的CakePHP视图方法,php,cakephp,Php,Cakephp,我的投资组合有以下链接结构: <?php echo $this->Html->link($post['Portfolio']['title'], array('controller' => 'portfolio', 'action' => 'view', Inflector::slug($post['Portfolio']['title'])), array('title' => $post['Portfolio']['title'])); ?> @R
<?php echo $this->Html->link($post['Portfolio']['title'], array('controller' => 'portfolio', 'action' => 'view', Inflector::slug($post['Portfolio']['title'])), array('title' => $post['Portfolio']['title'])); ?>
@Ross建议您使用Portfolio.slug进行搜索,下面是您可以做到的方法:
public function beforeSave(array $options = array())
{
// If the title is not empty, create/update the slug.
if ( ! empty($this->data[$this->alias]['title'] )
$this->data[$this->alias]['slug'] = Inflector::slug($this->data[$this->alias]['title']);
// Returning true is important otherwise the save or saveAll call will fail.
return true;
}
您的
$title
很可能无效(空格、无效字符等。您应该使用URL友好的slug,并将其传递给您的查看
函数。为了澄清,即使您在$title上使用屈折符::slug
,您的公文包。title
可能不会存储为slug。您需要搜索公文包。slug
,以确保matc好的,我明白了。你能告诉我怎么做吗?例如,在我的数据库中,标题将保存为“Paperview Magazine”,我能不能也在控制器中改变帖子标题,并对它们进行比较(因为它们将匹配)要获得正确的帖子?该方法的问题是,您必须获取整个投资组合记录并循环遍历它们,直到找到正确的记录。这将是非常低效的,尤其是随着数据库表的增长。我不是已经在使用find()
方法遍历它们了吗?不,find('first'))仅返回1行,而不是全部。要实现上述建议,您必须找到('all')并循环抛出每一行。好的,请参阅此处了解我的另一个想法:如果您能帮助完成此任务,那将非常棒,谢谢
public function beforeSave(array $options = array())
{
// If the title is not empty, create/update the slug.
if ( ! empty($this->data[$this->alias]['title'] )
$this->data[$this->alias]['slug'] = Inflector::slug($this->data[$this->alias]['title']);
// Returning true is important otherwise the save or saveAll call will fail.
return true;
}