【问题标题】:CodeIgniter URL Route with ID and title带有 ID 和标题的 CodeIgniter URL 路由
【发布时间】:2018-12-13 13:08:19
【问题描述】:

我是 CodeIgniter 的新手 我想更改我的网址

http://test.com/1/test-post

http://test.com/test-post-1

在带有路由的 CI 中。我如何通过 URL Route 实现这一点?

我的表格帖子

posts_id
posts_name

我的主页视图(调用帖子)

我使用 url 标题作为 url:

<a href="<?php echo base_url("{$v['posts_id']}/".url_title($v['posts_name'], "-", true)) ?>">

我的帖子控制器

    <?php 
defined('BASEPATH') OR exit ('No direct script access allowed');
class Posts extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Posts_model');
    }
    public function index()
    {
        show_404();
    }
    public function details($posts_id=NULL,$posts_name='') {
        $data['title'] = $this->Posts_model->select_content_by_id($posts_id);
        $data['data'] = $this->Posts_model->select_content_by_id($posts_id);
        $this->load->view('posts',$data);
    }
}

我的帖子模型

 <?php 
defined('BASEPATH') OR exit ('No direct script access allowed');
class Posts_model extends CI_Model{
    public function dsPosts()
    {
        return $this->db->get('posts')->result_array();
    }
    public function select_content_by_id($posts_id)
    {
        return $this->db->where('posts_id',$posts_id)->get('posts')->result_array();
    }
}

我的路线

$route['default_controller'] = 'home';
$route['404_override'] = '';
$route['(:num)'] = 'posts/details/$1';
$route['(:num)/(:any)'] = 'posts/details/$1/$2';

【问题讨论】:

    标签: php codeigniter codeigniter-3


    【解决方案1】:

    你已经接近答案了

    $route['(:any)-(:num)'] = 'posts/details/$2/$1';
    

    然后在视图中

    <a href="<?php echo base_url(url_title($v['posts_name'], "-", true)."-{$v['posts_id']}".) ?>">
    

    就是这样。但我建议你写得更清楚 url 因为你可以有多个控制器!如果您有 cmets 控制器并想从中获取数据会怎样? (:any) 表示它可以是任何东西

    【讨论】:

    • 谢谢!它的工作。我忘了检查输入ID...所以我在$1 和$2 上犯了一个错误!
    猜你喜欢
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多