【问题标题】:Filtering Results with CodeIgniter使用 CodeIgniter 过滤结果
【发布时间】:2011-09-18 08:56:52
【问题描述】:

我有两个表书和作者。使用 CodeIgniter,我希望用户能够过滤结果 - 例如,显示 author_id = 'x' 和 book_lang = 'y' 和 publication_year = '2000' 的结果。过滤条件值来自用户通过下拉列表。

使用 codeigniter 助手和绑定等生成查询的最佳方法是什么?

例如,下面的查询将为我提供 author_id= 1 的所有内容。例如,如果过滤器是混合的会怎样;作者_id = 1; language = 'all' (不要在语言上放置 where 子句)和 publication year = 'all' 也不要放置 where 子句。我是否需要手动检查值和代码,或者是否有一个 codigniter 辅助方法允许如果下拉值为“全部显示”,过滤器将从 where 子句中删除?

$sql = "select * from AUTHORs a , BOOKS b where 
        a.AUTH_ID = b.BOOK_AUTH_ID 
        and b.BOOK_AUTH_ID = ? 
        and b.BOOK_LANGUAGE = ?
        and b.PUB_YEAR = ? ";

$query =  $this->db->query($sql, array ($author_id, $book_lang, $pub_year));

【问题讨论】:

    标签: codeigniter filter


    【解决方案1】:

    您应该使用 Codeigniter 的 Active Record 类来构建您的查询:

    $this->db->select('*');
    $this->db->from('AUTHORs a , BOOKS b');
    $this->db->where('a.AUTH_ID', 'b.BOOK_AUTH_ID');
    
    if ($author_id != 'all') $this->db->where('b.BOOK_AUTH_ID', $author_id);
    if ($book_lang != 'all') $this->db->where('b.BOOK_LANGUAGE', $book_lang);
    if ($pub_year != 'all') $this->db->where('b.PUB_YEAR', $pub_year);
    
    $query = $this->db->get();
    

    要了解有关 Codeigniter 的 Active Record 类的更多信息,请访问文档:
    http://codeigniter.com/user_guide/database/active_record.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 2019-09-17
      • 2019-12-28
      相关资源
      最近更新 更多