简体   繁体   English

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

[英]How can I do this database query in Codeigniter?

I want to create a browse method for my CodeIgniter model. 我想为我的CodeIgniter模型创建一个浏览方法。 I wrote one, but it generates a bad SQL. 我写了一个,但是它生成了一个错误的SQL。 Here is my Code: 这是我的代码:

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);
}

I want to generate an sql like this: 我想生成一个这样的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

But it seems CodeIgniter adds an extra " 1 " after `distance` < 20. Why is this happening? 但是似乎CodeIgniter在`distance` <20之后增加了一个额外的“ 1 ”。为什么会这样?

This is the output of my page: 这是我页面的输出: 在此处输入图片说明

The "1" is from the true that you provide as the second argument $value where you set your having part of the query. 在“1”是从true您提供的第二个参数$value在那里您将having查询的一部分。

The documentation states the arguments as: 该文档将参数声明为:

having($key[, $value = NULL[, $escape = NULL]])

If you are intending to say true to $escape , you may do: 如果您打算对$escapetrue ,则可以执行以下操作:

$this->db->having("distance <", $maxDistance, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM