我需要一些指导。我正在使用Codeigniter 3. 由于它是带段路由的MVC fw,我想知道如何创建自定义路由,它将显示只有name
的记录(可以是类别,产品,帖子等)。从数据库而不是id/name
当我需要id segment
来标识哪个数据库记录我需要返回或通过id
预览。如何覆盖Codeigniter 3路由,以显示名称而不是id和名称
我会发布一些代码示例:
控制器
class Categories extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('CategoryM');
}
public function index(){
$data = array(
'category_list' => $this->CategoryM->listAll()
);
$this->load->view('test/category_list', $data);
}
public function preview()
{
$categoryId = $this->uri->segment(2);
$data = array (
'previewByCategory' => $this->CategoryM->previewByCategory($categoryId)
);
$this->load->view('public/preview_by_category', $data);
}
型号
<?php
class CategoryM extends CI_Model {
public function listAll() {
$query = $this->db
->select('*')
->from('categories')
->where('parentid', NULL, TRUE)
->order_by('name', 'asc')
->get();
if($query->num_rows() > 0) {
return $query->result();
}else{
return false;
}
public function previewByCategory($categoryId=''){
$query = $this->db
->select(/* posts and categories data */)
->from('categories')
->join('posts', 'posts.categoryID = categories.id', 'left')
->where('categories.id', $categoryId)
->get();
if($query->num_rows() > 0){
return $query->result();
}else{
return false;
}
}
}
查看
<?php if($category_list):?>
<?php foreach($category_list as $category):?>
<h3>
<a href="<?php echo base_url() . strtolower(url_title($category->name) . '/' . $category->id);?>">
<?php echo $category->name;?>
</a>
</h3>
<?php endforeach;?>
<?php endif;?>
我的路线
// Category routes
$route['categories'] = 'categories/index';
$route['(:any)/(:num)'] = 'categories/preview/$1';
我要的是不是路线
www.mywebsite/categoryname/categoryid/
只显示
www.mywebsite/categoryname
这将列出所有产品从类别组。但如何做到这一点没有在URL中的ID。如果我的问题太宽泛,我很抱歉。提前致谢。
如果那些只是 –
独特如何你的意思是你可以做到这一点'categoryname'?要根据类别名称的值获取数据而不使用ID? – Goran