【问题标题】:Can someone help me rewrite this query string to CodeIgniter active record有人可以帮我将此查询字符串重写为 CodeIgniter 活动记录吗
【发布时间】:2013-08-24 04:47:19
【问题描述】:

请帮帮我:

SELECT * 
FROM  `product` 
WHERE  `vi_name` LIKE  '%product%'
OR  `en_name` LIKE  '%product%'
AND `parent_id` != 0

我编写了自己的代码,但它仍然计算行数的方式有 parent_id = 0

function get_product_by_search_slug($slug) {
        $this -> db -> from('product');
        $this -> db -> like('vi_name', $slug);
        $this -> db -> or_like('en_name', $slug);
        $this -> db -> where_not_in('parent_id', 0);
        $query = $this -> db -> get();
        return $query -> result();
}

我有一个解决方案,它工作正常,但不知何故我不太满意:

function get_product_by_search_slug($slug) {
        $this -> db -> select("* FROM `product` WHERE `vi_name` LIKE '%". $slug ."%' OR `en_name` LIKE '%". $slug ."%' AND `parent_id` != 0");
        $query = $this -> db -> get();
        return $query -> result();
}

【问题讨论】:

  • "AND parent_id != 0".. != 对于 SQL 不正确。使用<> 或NOT IN
  • 一旦你在查询中使用了 OR,你就需要大括号,所以它不能纯粹写在活动记录中,你需要像 ->where('(vi_name like '%something% ' OR en_name like '%something%)', NULL, FALSE)->where('parent_id !=', 0)
  • @DavidStarkey 我正在使用 mySQL,不知何故它可以工作。
  • @ahmad 我仍然没有完全理解你的想法。你能从我的案例中写一个演示吗?我会更加感激。谢谢你。

标签: codeigniter


【解决方案1】:

你可以试试这个

where('parent_id !=','0')

如果您遇到任何问题,请告诉我

【讨论】:

    【解决方案2】:

    试试这个

    $this->db->like('vi_name', $slug)
             ->or_like('en_name', $slug)
             ->where('parent_id <>', 0);
    

    【讨论】:

      【解决方案3】:
      $slugQ = $this->db->escape_like_str($slug);
      $this->db
          ->select('*')
          ->from('product')
          ->where("(vi_name like '%$slugQ%' OR en_name like '%$slugQ%')", NULL, FALSE)
          ->where('parent_id !=', 0)
          ->get()
          ->result();
      

      在我的示例中,我已经成功地避开了 slug 以进行正确的 mysql 查找,您必须自己进行一些额外的检查。

      【讨论】:

        猜你喜欢
        • 2014-10-10
        • 1970-01-01
        • 1970-01-01
        • 2016-01-08
        • 2022-01-27
        • 2016-03-10
        • 1970-01-01
        • 2020-10-05
        相关资源
        最近更新 更多