ThinkPHP3.1 Quick Start (4) consistent operation

Source: Internet
Author: User
In the previous article, we described the use of query language in detail, but the query language only solved the problem of query or operation condition, and more cooperation also needed to use the coherent operation method provided by the model.

Introduced

Coherent operations can effectively improve the code clarity and development efficiency of data access, and support all curd operations, as well as a bright spot in the thinkphp ORM. Use is also relatively simple, if we now want to query a user table to meet the status of 1 of the first 10 records, and want to be sorted by the creation time of users, the code is as follows:

$User->where (' Status=1 ')->order (' Create_time ')->limit ()->select ();

Here the Where, order, and limit methods are called coherent operations, except that the Select method must be placed last (because the Select method is not a coherent operation method), and the sequence of method calls for the coherent operation is not sequential, for example, the following code is equivalent to the above:

$User->order (' create_time ')->limit->where (' Status=1 ')->select ();

In fact, not only the query method can use coherent operations, including all curd methods can be used, for example:

$User->where (' id=1 ')->field (' Id,name,email ')->find ();

$User->where (' Status=1 and Id=1 ')->delete ();

The coherent operation will automatically clear all the values of the coherent operation when the second query or operation is complete (there are individual special coherent operations that record current values, such as the cache coherence operation). In short, the results of a coherent operation are not brought into future queries.
The coherent operating methods supported by the system are:

Method

Role

Supported parameter types

Where the definition string, array, and object used to query or update conditions

Table defines the string and array of data table names to manipulate

Alias is used to define the aliases string for the current data table

Data object assignment arrays and objects before data is added or updated

field defines the fields to query (support field exclusions) strings and arrays

Order is used to sort the results by string and array

Limit is used to restrict the number of query result strings and numbers

Page is used to query paging (internally converted to limit) strings and numbers

Group support string for the query

Having a having support string for the query

Join* for join support strings and arrays for queries

Union* used to support strings, arrays, and objects for the Union of Queries

Distinct distinct support for querying Boolean values

Lock mechanism Boolean value for the database

Cache supports multiple parameters for query caching (later described in detail in the cache section)

Relation for associative queries (requires associated model extension support) strings

Validate for data auto-validation arrays

Auto for data auto-complete array

Filter for data filtering strings

scope* for naming range strings, arrays

All coherent operations return the current model instance object (this), where the representation with the * identity supports multiple invocations.

Usage

Since the use of coherent operations often involves the use of multiple methods, here are some basic uses for each coherent operation:

WHERE

Where is used to query or update the definition of a condition

Usage where ($where)

parameter where (required): query or Operation condition, support strings, arrays, and objects

Return value Current Model instance

Note If the Where method is not called, the update and delete operations are not performed by default

The Where method is the most consistent method of operation, for more detailed usage please refer to: Quick Start (3) query language.


TABLE

Table defines the name of the data table to manipulate, dynamically changes the data table name of the current operation, needs to write the full name of the data table, contains prefixes, can use aliases and cross-Library operations

Usage table ($table)

Parameter table (required): Data table name, support for manipulating multiple tables, supporting strings, arrays, and objects

Return value Current Model instance

Note If you do not call the table method, the data table corresponding to or defined by the model is automatically obtained

Usage examples:

$Model->table (' think_user user ')->where (' status>1 ')->select ();

You can also cross-library operations in the table method, for example:

$Model->table (' db_name.think_user user ')->where (' status>1 ')->select ();

The parameters of the table method support the use of strings and arrays, array mode:

$Model->table (' think_user ' = ' user ', ' think_group ' = ' group ')->where (' status>1 ')->select ();

The advantage of using an array approach is to avoid situations where errors occur because of table name and keyword collisions.
In general, you do not need to call the table method, which automatically gets the data table that corresponds to or is defined by the current model.

DATA

Data can be used to assign values before new or saved data

Usage data ($data)

Parameter data (required): Database, array and object support

Return value Current Model instance

Note If you do not call the data method, either the current data object or the input to add and save will be taken

Examples of Use:

$Model->data ($data)->add ();

$Model->data ($data)->where (' id=3 ')->save ();

The parameters of the data method support objects and arrays, and if the objects are automatically converted into arrays. If you do not define a data method assignment, you can also use the Create method or manually assign a value to the object.

The data method of the model can also read the current data object, in addition to creating the object.
For example:

$this->find (3);

$data = $this->data ();

FIELD

field to define the fields to query

Usage field ($field, $except =false)

Parameters

Fields (required): field names, support for strings and arrays, support for specifying field aliases, or true for all fields of an explicit or data table.

Except (optional): whether to exclude, default to False, or true to indicate that the field defined for the data table excludes all fields other than the field parameter definition.

Return value Current Model instance

Note If you do not call the field method, all fields are returned by default, and field (' * ') is equivalent

Examples of Use:

$Model->field (' Id,nickname as Name ')->select ();

$Model->field (Array (' ID ', ' nickname ' = ' name '))->select ();

It is equivalent to using field (' * ') if you do not call the field method or if the field method passed in with null arguments.
If you need to explicitly pass in all of the fields, you can use the following method:

$Model->field (True)->select ();

However, we recommend that you only get field names that require explicit, or that are defined by field exclusions, for example:

$Model->field (' status ', True)->select ();

Indicates that all fields except status are obtained.

ORDER

Order is used to sort the result of the operation

Usage order ($order)

Parameter order (required): Sort field names, support strings and arrays, support multiple field sorting

Return value Current Model instance

Note If you do not call the order method, follow the default rules of the database

Examples of Use:

Order (' id desc ')

Sorting methods support sorting of multiple fields

Order (' Status desc,id ASC ')

The parameters of the order method support strings and arrays, with the following usage:

Order (Array (' status ' = ' desc ', ' ID '))

LIMIT

Limit is used to define the result limits to be queried (all database types are supported)

Usage limit ($limit)

Parameter limit (required): Limit quantity, support string

Return value Current Model instance

Note If you do not call the limit method, it means that there is no limit

Note If you do not call the limit method, it means that there is no limit
We know that the limit usage of different database types is not the same, but in thinkphp usage there is always a unified approach, that is, limit (' offset,length '), whether it is MySQL, SQL Server, or Oracle database, In this way, the system's database-driven classes are responsible for resolving this differentiation.
Examples of Use:

Limit (' 1,10 ')

You can also use the following notation, which is equivalent:

Limit (1,10)

If you use

Limit (' 10 ')

is equivalent to

Limit (' 0,10 ')

PAGE

Page is used to define the paging of data to be queried

Usage page ($page)

Parameter page (required): paging, supporting string

Return value Current Model instance

Remark None

The page action method is a new feature that allows for faster paging queries.
The use of the page method is similar to the Limit method in the following format:

Page (' page[,listrows] ')

The page represents the current number of pages, and ListRows indicates how many records are displayed per page. For example:

Page (' 2,10 ')

To show that 10 records per page are displayed, get the data on page 2nd.
The following syntax is equivalent:

Page (2,10);

ListRow reads the value of limit (' length ') if it is not written, for example:

Limit (->page) (3);

To show that 25 records per page are displayed, get the data on page 3rd.
If limit is not set, the default is to show 20 records per page.
The page method adds support for a second parameter, for example:

$this->page (5,25)->select ();

and the previous usage

$this->limit (' 5,25 ')->select ();

Equivalent.

GROUP

Group query support for the database

Usage Group ($group)

Parameter group (required): Field name of group, support string

Return value Current Model instance

Remark None

Examples of Use:

Group (' user_id ')

The parameters of the group method only support strings

Having

Having a having query support for a database

Usage ($having)

Parameter having (must): having, supporting string

Return value Current Model instance

Remark None

Examples of Use:

Having (' user_id>0 ')

The parameters of the having method only support strings

JOIN

Join join query support for the database

Usage Join ($join)

Parameter join (required): Join operation, support string and array

Return value Current Model instance

Note the Join method supports multiple calls

Examples of Use:

$Model->join (' work in artist.id = Work.artist_id ')->join (' card on artist.card_id = Card.id ')->select ();

By default, the left join method, if you need to use a different join method, you can change to

$Model->join (' Right join work on artist.id = work.artist_id ')->select ();

The Join method can only be used once if the parameters of the join method are in an array, and cannot be mixed with the string method.
For example:

Join (Array (' work on artist.id = work.artist_id ', ' card on artist.card_id = Card.id '))

UNION

Union union query support for the database

Usage Union ($union, $all =false)

Parameter Union (required): union operation, supporting strings, arrays, and objects
All (optional): If the Union ALL operation is used, the default is False

Return value Current Model instance

Note the Union method supports multiple calls

Examples of Use:

$Model->field (' name ')

->table (' Think_user_0 ')

->union (' SELECT name from think_user_1 ')

->union (' SELECT name from think_user_2 ')

->select ();

Array usage:

$Model->field (' name ')

->table (' Think_user_0 ')

->union (Array (' field ' = ' name ', ' table ' = ' think_user_1 '))

->union (Array (' field ' = ' name ', ' table ' = ' think_user_2 '))

->select ();

Or

$Model->field (' name ')

->table (' Think_user_0 ')

->union (Array (' Select name from think_user_1 ', ' select name from think_user_2 '))

->select ();

The union ALL operation is supported, for example:

$Model->field (' name ')

->table (' Think_user_0 ')

->union (' SELECT name from think_user_1 ', true)

->union (' SELECT name from Think_user_2 ', true)

->select ();

Or

$Model->field (' name ')

->table (' Think_user_0 ')

->union (Array (' Select name from think_user_1 ', ' select name from Think_user_2 '), true)

->select ();

Each Union method is equivalent to a separate SELECT statement.
Note: The SELECT statement inside the UNION must have the same number of columns. The column must also have a similar data type. Also, the order of the columns in each SELECT statement must be the same.

DISTINCT

Distinct unique filtering when querying data

Usage distinct ($DISTINCT)

Parameter distinct (required): whether distinct is used, Boolean value is supported

Return value Current Model instance

Remark None

Examples of Use:

$Model->distinct (True)->field (' name ')->select ();

LOCK

Lock for query or write locking

Usage Lock ($lock)

Parameter lock (required): Whether a lock is required, a Boolean value is supported

Return value Current Model instance

Note the Join method supports multiple calls

The lock method is a locking mechanism for a database, if used when querying or performing operations:

Lock (True)

The resulting SQL statement is automatically added at the end of the for update or for update NOWAIT (Oracle database).

VALIDATE

Validate for automatic validation of data

Usage Validate ($validate)

Parameter validate (required): auto-Validate definition

Return value Current Model instance

Notes can only be used with the Create method

The Validate method is used for automatic validation of data, which we will describe in detail in the Data validation section.

AUTO

Auto for data completion

Usage Auto ($auto)

Parameter Auto (required): Define auto-complete

Return value Current Model instance

Note the Auto method can only be used with the Create method

The Auto method is used for automatic data completion, which we will describe in the Data AutoComplete section.

SCOPE

Scope used for naming ranges of models

Usage scope ($scope)

Parameter scope (required): Named range definition

Return value Current Model instance

Note the scope method is actually predefined for coherent operations

The specific use of the scope method can be referenced in the following: 3.1 new feature naming range

FILTER

Filter for safe filtering of data

Usage filter ($filter)

Parameter filter (required): Filter Method Name

Return value Current Model instance

Note The filter method is typically used for write and update operations

The filter method is used for security filtering of data objects, such as:

$Model->data ($data)->filter (' Strip_tags ')->add ();

Currently the filter method does not support filtering of multiple methods.

Summarize

Coherent operation has brought great convenience to our data operation, and as long as the operation that SQL can achieve, basically can be implemented with thinkphp coherent operation, and do not consider the difference of expression between the database, have portability. We'll explain how to manipulate and get variables later.

The above is the ThinkPHP3.1 Quick Start (4) coherent operation of content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.