SQL query thinkphp

Source: Internet
Author: User

http://doc.thinkphp.cn/manual/query.html SQL query thinkphp built-in ORM and ActiveRecord mode for convenient data access operations, And the new version of the added coherence operation is to make this data operation more clear, but thinkphp still retains the native SQL query and execution operation support, in order to meet the needs of complex queries and some special data operations, the return value of SQL query is directly returned by the DB class query results, Did not do any of the processing. The following two methods are mainly included:
1. Query method
Query Execute SQL query operation
Usage Query ($sql, $parse =false)
Parameters Query (required): The SQL statement to query
Parse (optional): Whether to parse SQL
return value

Returns false if data is illegal or query error


Otherwise, the query result dataset is returned (same as the Select method)

Examples of Use:
    1. $Model = new model() //Instantiate a model object without any data table
    2. $Model, query("select * from Think_user where Status=1");
If you are currently using a distributed database and have read-write separation, the query method is always executed at the read server, so the query method corresponds to a read operation, regardless of your SQL statement.2. Execute Method
Execute SQL operations for updating and writing data
Usage Execute ($sql, $parse =false)
Parameters Query (required): The SQL statement to execute
Parse (optional): Whether to parse SQL
return value Returns false if data is illegal or query error
Otherwise, the number of records affected is returned
Examples of Use:
    1. $Model = new model() //Instantiate a model object without any data table
    2. $Model, execute("Update think_user set name= ' thinkphp ' where Status=1");
If you are currently using a distributed database, and you have set up read-write separation, the Execute method is always executed on the write server, so the Execute method corresponds to a write operation, regardless of your SQL statement.3. Other Skills
Get the current table name automatically
It is common to use native SQL to manually add the table name that is currently being queried, and if your table name changes later, you will need to modify the SQL statement for each native SQL query, and the system provides a small trick to help solve the problem.
For example:
    1. $model = M("User");
    2. $model, query(' select * from __table__ where status>1 ');
We use a string such as __table__, the system will automatically replace the current model corresponding table name when parsing, so that even if the model corresponding table name changes, you still do not have to modify the original SQL statement.

Supports coherent operations and SQL parsing
The new version adds a second parameter support to query and execute two native SQL operations, indicating whether SQL needs to be parsed (the default is false for direct execution of SQL), and if set to true resolves a special string in SQL (requires a coherent operation).
For example, the following wording is supported:
  1. $modelTable("Think_user")
  2. , where(array("name"= "thinkphp"))
  3. --field ("Id,name,email")
  4. -* Query(' select%field% from%table%%where% ',true);
Where the%field%,%table%, and%where% strings in the query method are automatically replaced with the parsed result SQL of a coherent operation method with the same name, the supported replacement strings are:
Replace string corresponding coherent operation method
%field% Field
%table% Table
%distinct% Distinct
%where% where
%join% Join
%group% Group
%having% Having
%order% Order
%limit% Limit
%union% Union
3Dynamic query with the PHP5 language features, thinkphp implements dynamic queries, including the following:
Method Name Description Example
Getby Querying data based on the value of a field For example, Getbyname,getbyemail
Getfieldby Query and return the value of a field based on a field For example, Getfieldbyname
Top How many records to get before (advanced model support is required) For example, TOP8,TOP12
First, getby dynamic query
The query is queried for the fields of the data table. For example, if the user object has properties such as id,name,email,address, then we can use the following query method to query the qualifying records directly based on a property.
    1. $user = $Usergetbyname(' liu21st ');
    2. $user = $Usergetbyemail(' [email protected] ');
    3. $user = getbyaddress(' Shenzhen, China ') $User
Dynamic query methods that do not support multiple data fields temporarily, use the Find method and the Select method to query.Second, getfieldby dynamic query
Query for a field and return the value of a field, such as
    1. $user = $Usergetfieldbyname(' liu21st ',' id ');
Represents the ID value of the user that is obtained based on the user's name.third, top dynamic query
Thinkphp also provides another way to dynamically query, which is to get the first N records that match the condition (as well as the location query, which requires that the current model class must inherit the advanced model class before it can be used). For example, we need to get the top 5 users in the current user with points greater than 0 and the highest points:
    1. $User, where(' score>80 '),order(' score desc '),TOP5 ();
The first 8 bits to get the points can be changed to:
    1. $User, where(' score>80 '),order(' score desc ') TOP8();
5Sub-query new version of the new sub-query support, there are two ways to use:
1. Using the Select method
When the parameter of the Select method is false, it means that no query is simply returned to the build SQL, for example:
    1. //  first constructs subquery sql 
    2. $subQuery  =  $model -> field ( ' id,name ' ) table ( ' tablename ' ) group ( ' field ' ( $where )->order ( ' status ' select false
2. Using the BuildSQL method
    1. $subQuery = $modelfield('id,name '), table (' tablename ')- >Group(' field '),where($where), order(' status ' ),buildsql();
When the BuildSQL method is called, the actual query operation is not performed, but only the SQL statement that generated the query (in order to avoid confusion, the parentheses are added to the SQL), and then we call directly in subsequent queries.
    1. Querying with subqueries
    2. ($model,table($subQuery.' A '), where (),Order(), Select()
The constructed subquery SQL can be used for the coherent operation of TP, such as table where and so on.

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.