假设我有这个数据库表模式:
id | article | slug
1 hey guys how are you? hey-guys-how-are-you?
我正在尝试保持我的数据库路由字段唯一
路线总是像这样骆驼化的消息字段this-is-a-title-but-now-is-a-route
所以插入相同的路线会产生db error of duplicated key
那么哪个是控制和插入始终唯一路线的好习惯?
谢谢
假设我有这个数据库表模式:
id | article | slug
1 hey guys how are you? hey-guys-how-are-you?
我正在尝试保持我的数据库路由字段唯一
路线总是像这样骆驼化的消息字段this-is-a-title-but-now-is-a-route
所以插入相同的路线会产生db error of duplicated key
那么哪个是控制和插入始终唯一路线的好习惯?
谢谢
因为您已经标记了 CodeIgniter,所以我建议您预先检查 slug 字段的值,然后在需要时增加该值。CI字符串助手有一个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
等等
您可以使用 php 的uniqid并且可能使用更多的熵来为您完成这项工作。
此函数的返回值始终具有相同的长度。否则使用更多的熵它的 23 和 13。因此,您可以随时轻松地替换 slug 以获得实际的东西。
此方法创建一个循环来增加 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;
}