CodeIgniter 用户指南 版本 1.6.3

编辑文档、查看近期更改请 登录注册  找回密码
查看原文

Active Record 类

CodeIgniter 使用的是修改过的Active Record数据库模式。 这种模式是以较少的程序代码来实现信息在数据库中的获取,插入,更改。 有时只用一两行的代码就能完成对数据库的操作。 CodeIgniter不需要每一个数据库表拥有自己的类。它提供了一个更简单的接口。

不只是简单,使用Active Record的一个主要的优点是允许你创建独立的数据库应用程序,因为查询语法是由数据库的适配器来产生的。它可以进行更安全的查询,因为系统会自动的对所有的输入值进行转义。

注意: 你如果想要写自己的查询表达式,可以在数据库配置文件中禁止这个类。同时相比 Active Record,使用核心数据库类库和适配器将会使用更少资源。

 

选择数据

下面的函数帮助你构建SQLSELECT语句。

备注:如果你正在使用 PHP5,你可以在复杂情况下使用链式语法。本页面底部有具体描述。

$this->db->get();

运行选择查询语句并且返回结果集。可以获取一个表的全部数据。

$query = $this->db->get('mytable');

// Produces: SELECT * FROM mytable

第二和第三个参数允许你设置一个结果集每页纪录数(limit)和结果集的偏移(offset)

$query = $this->db->get('mytable', 10, 20);

// Produces: SELECT * FROM mytable LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)

注意:第二参数是每页纪录数,第三个参数是偏移

你会注意到上面的函数由一个变量$query执行,这个$query可以用来显示结果集。

$query = $this->db->get('mytable');

foreach ($query->result() as $row)
{
    echo $row->title;
}

请访问查询结果页查看详细的生成结果的方法。

$this->db->get_where();

跟上面的函数一样,只是它允许你在函数的第二个参数那里添加一个 where 从句,从而不用使用 db->where() 这个函数:

$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

请阅读下面的 where 函数了解更多。

注意: get_where() 在以前的版本中写作 getwhere(),这是已经过时的用法。

$this->db->select();

允许你在SQL查询中写 SELECT 部分:

$this->db->select('title, content, date');

$query = $this->db->get('mytable');

// Produces: SELECT title, content, date FROM mytable

注意: 如果你你要查询表中的所有行,你可以不用写这个函数。省略后,CodeIgniter 会认为你要查询 全部行(SELECT *)。

$this->db->select() 可接受一个可选的第二个参数。如果你把它设为FALSE, CodeIgniter 将不会使用反引号保护你的字段或者表名 。这在进行复合查询时很有用。

$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
$query = $this->db->get('mytable');

$this->db->select_max();

为你的查询编写一个 "SELECT MAX(field)"。你可以选择性的给出第二个参数,以便重命名结果字段名。

$this->db->select_max('age');
$query = $this->db->get('members');
// Produces: SELECT MAX(age) as age FROM members

$this->db->select_max('age', 'member_age');
$query = $this->db->get('members');
// Produces: SELECT MAX(age) as member_age FROM members

$this->db->select_min();

Writes a "SELECT MIN(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

$this->db->select_min('age');
$query = $this->db->get('members');
// Produces: SELECT MIN(age) as age FROM members

$this->db->select_avg();

Writes a "SELECT AVG(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

$this->db->select_avg('age');
$query = $this->db->get('members');
// Produces: SELECT AVG(age) as age FROM members

$this->db->select_sum();

Writes a "SELECT SUM(field)" portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.

$this->db->select_sum('age');
$query = $this->db->get('members');
// Produces: SELECT SUM(age) as age FROM members

$this->db->from();

Permits you to write the FROM portion of your query:

$this->db->select('title, content, date');
$this->db->from('mytable');

$query = $this->db->get();

// Produces: SELECT title, content, date FROM mytable

Note: As shown earlier, the FROM portion of your query can be specified in the $this->db->get() function, so use whichever method you prefer.

$this->db->join();

Permits you to write the JOIN portion of your query:

$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');

$query = $this->db->get();

// Produces:
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id

Multiple function calls can be made if you need several joins in one query.

If you need something other than a natural JOIN you can specify it via the third parameter of the function. Options are: left, right, outer, inner, left outer, and right outer.

$this->db->join('comments', 'comments.id = blogs.id', 'left');

// Produces: LEFT JOIN comments ON comments.id = blogs.id

$this->db->where();

This function enables you to set WHERE clauses using one of four methods:

Note: All values passed to this function are escaped automatically, producing safer queries.

  1. Simple key/value method: $this->db->where('name', $name);

    // Produces: WHERE name = 'Joe'

    Notice that the equal sign is added for you.

    If you use multiple function calls they will be chained together with AND between them:

    $this->db->where('name', $name);
    $this->db->where('title', $title);
    $this->db->where('status', $status);

    // WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
  2. Custom key/value method:

    You can include an operator in the first parameter in order to control the comparison:

    $this->db->where('name !=', $name);
    $this->db->where('id <', $id);

    // Produces: WHERE name != 'Joe' AND id < 45
  3. Associative array method: $array = array('name' => $name, 'title' => $title, 'status' => $status);

    $this->db->where($array);

    // Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'

    You can include your own operators using this method as well:

    $array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);

    $this->db->where($array);
  4. Custom string:

    You can write your own clauses manually:

    $where = "name='Joe' AND status='boss' OR status='active'";

    $this->db->where($where);

$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.

$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);

$this->db->or_where();

This function is identical to the one above, except that multiple instances are joined by OR:

$this->db->where('name !=', $name);
$this->db->or_where('id >', $id);

// Produces: WHERE name != 'Joe' OR id > 50

Note: or_where() was formerly known as orwhere(), which has been deprecated.

$this->db->where_in();

Generates a WHERE field IN ('item', 'item') SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

$this->db->or_where_in();

Generates a WHERE field IN ('item', 'item') SQL query joined with OR if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->or_where_in('username', $names);
// Produces: OR username IN ('Frank', 'Todd', 'James')

$this->db->where_not_in();

Generates a WHERE field NOT IN ('item', 'item') SQL query joined with AND if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->where_not_in('username', $names);
// Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')

$this->db->or_where_not_in();

Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR if appropriate

$names = array('Frank', 'Todd', 'James');
$this->db->or_where_not_in('username', $names);
// Produces: OR username NOT IN ('Frank', 'Todd', 'James')

$this->db->like();

This function enables you to generate LIKE clauses, useful for doing searches.

Note: All values passed to this function are escaped automatically.

  1. Simple key/value method: $this->db->like('title', 'match');

    // Produces: WHERE title LIKE '&#xma;tch%'

    If you use multiple function calls they will be chained together with AND between them:

    $this->db->like('title', 'match');
    $this->db->like('body', 'match');

    // WHERE title LIKE '&#xma;tch%' AND body LIKE '&#xma;tch%
    If you want to control where the wildcard (%) is placed, you can use an optional third argument. Your options are 'before', 'after' and 'both' (which is the default). $this->db->like('title', 'match', 'before');
    // Produces: WHERE title LIKE '&#xma;tch'

    $this->db->like('title', 'match', 'after');
    // Produces: WHERE title LIKE 'match%'

    $this->db->like('title', 'match', 'both');
    // Produces: WHERE title LIKE '&#xma;tch%'
  2. Associative array method: $array = array('title' => $match, 'page1' => $match, 'page2' => $match);

    $this->db->like($array);

    // WHERE title LIKE '&#xma;tch%' AND page1 LIKE '&#xma;tch%' AND page2 LIKE '&#xma;tch%'

$this->db->or_like();

This function is identical to the one above, except that multiple instances are joined by OR:

$this->db->like('title', 'match');
$this->db->or_like('body', $match);

// WHERE title LIKE '&#xma;tch%' OR body LIKE '&#xma;tch%'

Note: or_like() was formerly known as orlike(), which has been deprecated.

$this->db->not_like();

This function is identical to like(), except that it generates NOT LIKE statements:

$this->db->not_like('title', 'match');

// WHERE title NOT LIKE '&#xma;tch%

$this->db->or_not_like();

This function is identical to not_like(), except that multiple instances are joined by OR:

$this->db->like('title', 'match');
$this->db->or_not_like('body', 'match');

// WHERE title LIKE '&#xma;tch% OR body NOT LIKE '&#xma;tch%'

$this->db->group_by();

Permits you to write the GROUP BY portion of your query:

$this->db->group_by("title");

// Produces: GROUP BY title

You can also pass an array of multiple values as well:

$this->db->group_by(array("title", "date"));

// Produces: GROUP BY title, date

Note: group_by() was formerly known as groupby(), which has been deprecated.

$this->db->distinct();

Adds the "DISTINCT" keyword to a query

$this->db->distinct();
$this->db->get('table');

// Produces: SELECT DISTINCT * FROM table

$this->db->having();

Permits you to write the HAVING portion of your query. There are 2 possible syntaxe, 1 argument or 2:

$this->db->having('user_id = 45');
// Produces: HAVING user_id = 45

$this->db->having('user_id', 45);
// Produces: HAVING user_id = 45

You can also pass an array of multiple values as well:

$this->db->having(array('title =' => 'My Title', 'id <' => $id));

// Produces: HAVING title = 'My Title', id < 45

If you are using a database that CodeIgniter escapes queries for, you can prevent escaping content by passing an optional third argument, and setting it to FALSE.

$this->db->having('user_id', 45);
// Produces: HAVING `user_id` = 45 in some databases such as MySQL
$this->db->having('user_id', 45, FALSE);
// Produces: HAVING user_id = 45

$this->db->or_having();

Identical to having(), only separates multiple clauses with "OR".

$this->db->order_by();

Lets you set an ORDER BY clause. The first parameter contains the name of the column you would like to order by. The second parameter lets you set the direction of the result. Options are asc or desc, or random.

$this->db->order_by("title", "desc");

// Produces: ORDER BY title DESC

You can also pass your own string in the first parameter:

$this->db->order_by('title desc, name asc');

// Produces: ORDER BY title DESC, name ASC

Or multiple function calls can be made if you need multiple fields.

$this->db->order_by("title", "desc");
$this->db->order_by("name", "asc");

// Produces: ORDER BY title DESC, name ASC

Note: order_by() was formerly known as orderby(), which has been deprecated.

Note: random ordering is not currently supported in Oracle or MSSQL drivers. These will default to 'ASC'.

$this->db->limit();

Lets you limit the number of rows you would like returned by the query:

$this->db->limit(10);

// Produces: LIMIT 10

The second parameter lets you set a result offset.

$this->db->limit(10, 20);

// Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)

$this->db->count_all_results();

Permits you to determine the number of rows in a particular Active Record query. Queries will accept Active Record restrictors such as where(), or_where(), like(), or_like(), etc. Example:

echo $this->db->count_all_results('my_table');
// Produces an integer, like 25

$this->db->like('title', 'match');
$this->db->from('my_table');
echo $this->db->count_all_results();
// Produces an integer, like 17

$this->db->count_all();

Permits you to determine the number of rows in a particular table. Submit the table name in the first parameter. Example:

echo $this->db->count_all('my_table');

// Produces an integer, like 25
 

Inserting Data

$this->db->insert();

Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

$data = array(
               'title' => 'My title' ,
               'name' => 'My Name' ,
               'date' => 'My date'
            );

$this->db->insert('mytable', $data);

// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

The first parameter will contain the table name, the second is an associative array of values.

Here is an example using an object:

/*
    class Myclass {
        var $title = 'My Title';
        var $content = 'My Content';
        var $date = 'My Date';
    }
*/

$object = new Myclass;

$this->db->insert('mytable', $object);

// Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')

The first parameter will contain the table name, the second is an associative array of values.

Note: All values are escaped automatically producing safer queries.

$this->db->set();

This function enables you to set values for inserts or updates.

It can be used instead of passing a data array directly to the insert or update functions:

$this->db->set('name', $name);
$this->db->insert('mytable');

// Produces: INSERT INTO mytable (name) VALUES ('{$name}')

If you use multiple function called they will be assembled properly based on whether you are doing an insert or an update:

$this->db->set('name', $name);
$this->db->set('title', $title);
$this->db->set('status', $status);
$this->db->insert('mytable');

set() will also accept an optional third parameter ($escape), that will prevent data from being escaped if set to FALSE. To illustrate the difference, here is set() used both with and without the escape parameter.

$this->db->set('field', 'field+1', FALSE);
$this->db->insert('mytable');
// gives INSERT INTO mytable (field) VALUES (field+1)

$this->db->set('field', 'field+1');
$this->db->insert('mytable');
// gives INSERT INTO mytable (field) VALUES ('field+1')

You can also pass an associative array to this function:

$array = array('name' => $name, 'title' => $title, 'status' => $status);

$this->db->set($array);
$this->db->insert('mytable');

Or an object:

/*
    class Myclass {
        var $title = 'My Title';
        var $content = 'My Content';
        var $date = 'My Date';
    }
*/

$object = new Myclass;

$this->db->set($object);
$this->db->insert('mytable');
 

Updating Data

$this->db->update();

Generates an update string and runs the query based on the data you supply. You can pass an array or an object to the function. Here is an example using an array:

$data = array(
               'title' => $title,
               'name' => $name,
               'date' => $date
            );

$this->db->where('id', $id);
$this->db->update('mytable', $data);

// Produces:
// UPDATE mytable
// SET title = '{$title}', name = '{$name}', date = '{$date}'
// WHERE id = $id

Or you can supply an object:

/*
    class Myclass {
        var $title = 'My Title';
        var $content = 'My Content';
        var $date = 'My Date';
    }
*/

$object = new Myclass;

$this->db->where('id', $id);
$this->db->update('mytable', $object);

// Produces:
// UPDATE mytable
// SET title = '{$title}', name = '{$name}', date = '{$date}'
// WHERE id = $id

Note: All values are escaped automatically producing safer queries.

You'll notice the use of the $this->db->where() function, enabling you to set the WHERE clause. You can optionally pass this information directly into the update function as a string:

$this->db->update('mytable', $data, "id = 4");

Or as an array:

$this->db->update('mytable', $data, array('id' => $id));

You may also use the $this->db->set() function described above when performing updates.

 

Deleting Data

$this->db->delete();

Generates a delete SQL string and runs the query.

$this->db->delete('mytable', array('id' => $id));

// Produces:
// DELETE FROM mytable
// WHERE id = $id

The first parameter is the table name, the second is the where clause. You can also use the where() or or_where() functions instead of passing the data to the second parameter of the function:

$this->db->where('id', $id);
$this->db->delete('mytable');

// Produces:
// DELETE FROM mytable
// WHERE id = $id

An array of table names can be passed into delete() if you would like to delete data from more then 1 table.

$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);

If you want to delete all data from a table, you can use the truncate() function, or empty_table().

$this->db->empty_table();

Generates a delete SQL string and runs the query. $this->db->empty_table('mytable');

// Produces
// DELETE FROM mytable

$this->db->truncate();

Generates a truncate SQL string and runs the query.

$this->db->from('mytable');
$this->db->truncate();
// or
$this->db->truncate('mytable');

// Produce:
// TRUNCATE mytable

Note: If the TRUNCATE command isn't available, truncate() will execute as "DELETE FROM table".

 Method Chaining

Method chaining allows you to simplify your syntax by connecting multiple functions. Consider this example:

$this->db->select('title')->from('mytable')->where('id', $id)->limit(10, 20);

$query = $this->db->get();

Note: Method chaining only works with PHP 5.

 

 Active Record Caching

While not "true" caching, Active Record enables you to save (or "cache") certain parts of your queries for reuse later. Normally, when an Active Record call is completed, all stored information is reset for the next call. With caching, you can prevent this reset, and reuse information easily.

Cached calls are cumulative. If you make 2 cached select() calls, and then 2 uncached select() calls, this will result in 4 select() calls. There are three Caching functions available:

$this->db->start_cache()

This function must be called to begin caching. All Active Record queries of the correct type (see below for supported queries) are stored for later use.

$this->db->stop_cache()

This function can be called to stop caching.

$this->db->flush_cache()

This function deletes all items from the Active Record cache.

Here's a usage example:

$this->db->start_cache();
$this->db->select('field1');
$this->db->stop_cache();
$this->db->get('tablename');
// Results in:
// SELECT `field1` FROM (`tablename`)

$this->db->select('field2');
$this->db->get('tablename');
// Results in:
// SELECT `field1`, `field2` FROM (`tablename`)

$this->db->flush_cache();

$this->db->select('field2');
$this->db->get('tablename');
// Results in:
// SELECT `field2` FROM (`tablename`)

Note: The following fields can be cached: ‘select’, ‘from’, ‘join’, ‘where’, ‘like’, ‘groupby’, ‘having’, ‘orderby’, ‘set’

 

 

翻译贡献者: aykirk, Hex, huanxiangwu, imjie, thankwsx
最后修改: 2008-11-17 11:05:38