使用帖子标题作为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进行搜索,下面是您可以做到的方法:

  • 在数据库表中添加一个名为slug的字段。您很可能需要一个长度足以容纳slug的VARCHAR
  • 当您创建或更新“公文包”记录时,请使用拐点::slug方法生成slug并将其保存到数据库中。您可以始终在模型的beforeSave事件中执行此操作,如果愿意,也可以在保存数据之前在控制器中执行此操作
  • 更新find调用以查找Portfolio.slug而不是Portfolio.title
  • 不幸的是,没有办法反转拐点::Slug函数,因为它会删除某些字符,如撇号、引号、括号等。这就是为什么如果要搜索Slug,需要将其保存到数据库中的原因

    以下是如何在模型中使用beforeSave事件:

    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;
    }