【问题标题】:Unique url slugs (routes)唯一的 url slugs(路由)
【发布时间】:2012-12-04 19:36:43
【问题描述】:

假设我有这个数据库表模式:

id |      article          | slug
1    hey guys how are you?  hey-guys-how-are-you?

我正在尝试保持我的数据库路由字段唯一

route 总是像这样this-is-a-title-but-now-is-a-route 骆驼化的消息字段@

所以插入相同的路由会产生一个db error of duplicated key

那么,什么是控制和插入始终唯一的路线的好习惯?

谢谢

【问题讨论】:

  • 例如,WordPress 会创建像 this-is-my-route-1this-is-my-route-2、...这样的页面 slugs。
  • @biziclop 是的,如何控制它? +1 、 +2 、 +3 .. 等背后的逻辑是什么?
  • 你控制是否存在然后放+1然后控制如果存在再放+2然后等等..或者其他?
  • 显然你的路由组件不是唯一的。仅保持 id 唯一,并在您的路线中使用它(可能像 SO 那样?)。
  • @didierc nope :( 我有明确的网址,例如 project/-my-project :( 不要转向 project/8374/my-project 请:D

标签: php mysql codeigniter unique slug


【解决方案1】:

此方法创建一个循环来增加 slug,直到找到一个不存在的。

在您的模型中:

public function create_slug($title) {
    $this->ci->load->helper('string');
    $this->ci->load->helper('url');

    $i = 1;
    $max = 10; 
    $slug = url_title($title, '-', TRUE);

    while($i <= $max && ($exist = $this->db->where('slug', $slug)->count_all_results('posts')) != 0) {
        $slug= increment_string($slug, '-');
        $i++;
    }

    //max was reached and the last slug is not unique
    if($i >= $max && $exist > 0) return FALSE;

    return $slug;
}

【讨论】:

  • 是的,你是对的。但对我来说,它不是由公众经营的。所以我为你改进了它。
【解决方案2】:

您可以利用 php 的 uniqid 并可能使用更多的熵来为您完成这项工作。

这个函数的返回值总是相同的长度。否则使用更多的熵它的 23 和 13。因此,您可以随时轻松地替换 slug 以获得实际的东西。

【讨论】:

  • 这听起来不错,如果没有更多答案,我一定会检查一下
  • 对不起,swatkins 最后说服了我 :P ,非常感谢你!
【解决方案3】:

因为您已经标记了 CodeIgniter,所以我建议您预先检查 slug 字段的值,然后在需要时增加该值。 CI string helper 有一个 increment_string 函数,它会为您处理这些问题。

increment_string()

通过向字符串附加数字或增加数字来增加字符串。用于创建“副本”或文件或复制具有唯一标题或 slug 的数据库内容。

使用示例:

echo increment_string('file', '_'); // "file_1"
echo increment_string('file', '-', 2); // "file-2"
echo increment_string('file-4'); // "file-5"

所以

this-is-a-route 变为 this-is-a-route-1

this-is-a-route-1 变为 this-is-a-route-2

等等

【讨论】:

  • 非常感谢 CI 提示,但问题实际上不是添加增量,这是背后的逻辑,我的意思是,控制是否存在,然后根据需要放置它,但是如果我有 -my-route- 然后 -my-route-1 在数据库中?如果我尝试再次插入 -my-route- 这应该变成 -my-route-2
  • 使用 sql LIKE 比较和 ORDER BY slug 很容易检查 -my-route-n 是否存在。例如:SELECT * FROM mytable WHERE slug LIKE '-my-route-%' ORDER BY slug DESC LIMIT 1 -> 这应该为您提供最高可用的“-my-route-n”,您可以通过 increment_string 函数运行它。
  • 这很简单,但性能不佳,如果您有数千条数据库记录怎么办?一个 sql LIKE 对于控制/插入一个蛞蝓来说太贵了,你不觉得吗? :P
  • 除非您正在索引您的 slug 字段,我假设您是,因为这是一个唯一字段并用于访问记录。
  • LIKE 运算符将使用索引作为术语部分直到第一个通配符。因为您的 sql 语句在术语末尾使用通配符,所以索引的性能应该与 = 比较一样好。
猜你喜欢
  • 2012-12-13
  • 2023-03-08
  • 2021-11-11
  • 2017-04-15
  • 2019-07-12
  • 2016-06-01
  • 2012-04-24
  • 2011-12-01
  • 1970-01-01
相关资源
最近更新 更多