日常问题之收集:CI框架篇(持续更新)

DISTINCT 写法

$this->db->select('DISTINCT(id)');

UNION 写法

不支持 UNION,自己拼 SQL 吧

save()、update()、save_batch()、update_batch()、update_by_where() 返回值

save

    public function save($data) {
        if ($this->db->insert($this->_table, $data)) {
            $insert_id = $this->db->insert_id();  //insert_id,数据表如果没有自增id会返回0
            if ($insert_id) {
                return $insert_id;
            } else {
                return $this->db->affected_rows();
            }
        }
        return 0;
    }

保存失败,返回0
保存成功,返回自增id,没有自增id,返回1

save_batch

public function save_batch($data) {
    if ($data) {
        $affected_rows = $this->db->insert_batch($this->_table,$data);
            return intval($affected_rows);
        }
        return 0;
    }

看代码,返回的是一个整数,表示保存成功的记录数量

update

public function update($data, $where) {
        if ( ! $data ) {
            return 0;
        }

        foreach ($where as $k => $v) {
            if (is_array($v)) {
                $this->db->where_in($k,$v);
                unset($where[$k]);
            }
        }
        $this->db->update($this->_table, $data, $where);
        return $this->db->affected_rows();
    }

返回更新成功的记录数

update_by_where

public function update_by_where($data = [], $where = [])
    {
        if ( ! $data OR ! $where) {
            return 0;
        }

        $this->db->stop_cache();
        $this->db->update($this->_table, $data, '1' . $this->_get_where($where));

        return $this->db->affected_rows();
    }

返回更新成功的记录数

update_batch

public function update_batch($data, $key) {
        if ( ! $data OR ! $key ) {
            return 0;
        }

        $affected_rows = $this->db->update_batch($this->_table, $data, $key);
        return intval($affected_rows);
    }

返回更新成功的记录数

条件嵌套查询,Query grouping

$this->db->select('*')->from('my_table')
        ->group_start()
                ->where('a', 'a')
                ->or_group_start()
                        ->where('b', 'b')
                        ->where('c', 'c')
                ->group_end()
        ->group_end()
        ->where('d', 'd')
->get();

// Generates:
// SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'

内部魔改

get_fields() offset limit 参数

get_fields(, , , , [$offset, $limit])

get_fields() 查不到数据时返回null还是空数组?

这个问题就转化为 result_array() 的返回值:

$this->db->query($sql)->result_array()

看文档描述:This method returns the query result as a pure array, or an empty array when no result is produced.

所以一定是返回数组类型的。

CLI:命令行执行

php /home/webserver/webapp//cron.php cron/ClueCitySummaryCron history

CLI:浏览器执行

脚本在浏览器执行:http:///api/cron/ClueCitySummaryCron/daily


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 jaytp@qq.com