0
  • 代码点火器 2.1.2

我有一个包含两种方法的类,用于这个问题showoneview. 后者返回一个小型数据库的所有项目,也可以执行搜索。另一个用于永久链接,例如domain.com/showone/firstname-lastname

<?php
class Pages extends CI_Controller {

public function view($page)
    {
    //this includes a mysql search
    }

public function showone($slug)
    {
    //abbreviated version:
    $query = "SELECT * FROM mytable WHERE slug = '" . $slug . "'";
    $result = $this->db->query($query);
    if ($result->num_rows() == 0)
        {
        //here is where I'd like to use the same search that I used in showall
        }
    else
        {
        //show the one item
        }
    }

} //class
?>

因此,如果用户决定直接输入一个不从数据库返回任何内容的 URL,我想将他引导到搜索结果而不是显示 404。

那么如何设置一个function searchdatabase($query)供两者使用的showoneview

4

2 回答 2

0

您可以在控制器中使用控制器功能:

public function view($page)
    {
       $this->showone($slug);
    }
于 2012-07-24T17:48:40.357 回答
0

在模型中定义该函数,加载模型,然后调用模型-> 方法。

<?php
//Your Model would look something like this.
class Search_Model extends CI_Model {

    public function __construct(){
      parent::__construct();
    }

    public function showone($slug)
    {
    //abbreviated version:
    //Its best to use active record for building your queries
    $this->db->where->('slug', $slug);
    $result = $this->db->get('mytable');
    if ($result->num_rows() == 0)
        {
        //here is where I'd like to use the same search that I used in showall
        }
    else
        {
        //show the one item
        }
    }

} //class

然后在你的控制器中你会这样做:

<?php
//Your Controllerwould look something like this.
class Index extends CI_Controller {
    public function __construct(){
      parent::__construct();
      //model will be loaded for each method.
      //if you're going to use this model across several controllers
      //its best to autoload it, set that in autoload.php under /app/config
      $this->load->model('search_model');
    }

    public function index(){
      $searchResults = $this->search_model->showone('slugone');
    }

更新

我刚刚意识到,如果没有返回结果,您想要显示所有结果。在这种情况下,您也将在模型中执行该逻辑..

在您的条件语句中,您将执行以下操作:

    if ($result->num_rows() == 0)
        {
        return $this->showall();
        }
    else
        {
        return $this->view($slug);
        }
    }

你的showall()view()方法会return $result->result();

于 2012-07-24T13:04:03.117 回答