如何在Codeigniter中进行此数据库查询?

时间:2018-10-21 22:47:03

标签: php sql codeigniter pdo

我想为我的CodeIgniter模型创建一个浏览方法。我写了一个,但是它生成了一个错误的SQL。这是我的代码:

public function browse($keyword = null, $category_id = null, $order = "ASC", $order_by = "expiration_date", $latitude = null, $longitude = null, $maxDistance = null)
{
    $this->db->select(" id,
        round(
            (
                6371 * acos(
                    cos(radians(10)) * cos(radians(latitude)) * cos(radians(20) - radians(longitude)) + sin(radians(10)) * sin(radians(latitude))
                )
            ),
            2
        ) AS distance", false);

    // Order:
    if (!in_array($order, array("ASC", "DESC", "RANDOM"))) {
        $order = "ASC";
    }
    if (!in_array($order_by, array("distance", "expiration_date", "id", "offer_datetime", "food_name", "food_category"))) {
        $order_by = "expiration_date";
    }

    if ($keyword != null && is_string($keyword)) {
        $this->db->group_start();
        $this->db->like("food_name", $keyword);
        $this->db->or_like("details", $keyword);
        $this->db->group_end();
    }

    if ($category_id != null && is_numeric($category_id)) {
        $this->db->where("food_category", $category_id);
    }

    if($maxDistance != null && is_numeric($maxDistance)){
        $this->db->having("distance < $maxDistance", true);
    }
    $this->db->order_by($order_by, $order);


    return $this->db->get(TABLE_NAME);
}

我想生成一个这样的sql:

SELECT id, round( ( 6371 * acos( cos(radians($latitude)) * cos(radians(latitude)) * 
cos(radians($longitude) - radians(longitude)) + sin(radians($latitude)) * 
sin(radians(latitude)) ) ), 2 ) AS distance FROM `TABLE_NAME` WHERE ( 
`food_name` LIKE '%keyword%' ESCAPE '!' OR `details` LIKE '%keyword%' ESCAPE '!' ) AND 
`food_category` = '1' HAVING `distance` < 20 ORDER BY `offer_datetime` DESC

但是似乎CodeIgniter在`distance` <20之后添加了额外的“ 1”。 为什么会这样?

这是我页面的输出: enter image description here

1 个答案:

答案 0 :(得分:1)

“ 1”来自您作为第二个参数cz提供的true,您在其中设置了查询的$value部分。

文档将参数声明为:

having

如果您打算对having($key[, $value = NULL[, $escape = NULL]]) true,则可以这样做:

$escape