ThinkPHP3.1 quick start (4) coherent operation
In the previous article, we described the usage of query language in detail, but query language only solves the problem of query or operation conditions. More cooperation requires the use of coherent operation methods provided by the model.
Introduction
Continuous operation can effectively improve the code clarity and development efficiency of data access, and supports all CURD operations. It is also a highlight of ThinkPHP's ORM. It is also relatively simple to use. If we now want to query the first 10 records of a User table that satisfy the status of 1, and want to sort by the user's creation time, the code is as follows:
$User->where('status=1' )->order('create_time')->limit(10)->select();
The where, order and limit methods here are called coherent operation methods, except that the select method must be placed last Except (because the select method is not a coherent operation method), the order of method calls for consecutive operations is not sequential. For example, the following code is equivalent to the above:
$User->order('create_time')->limit( 10)->where('status=1')->select();
In fact, not only query methods can use coherent operations, but 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 is only valid for the current query or operation. After completion, all the passed values of the coherent operation will be automatically cleared (there are some special coherent operations that will record the current passed values, such as cache coherent operations). In short, the results of a coherent operation are not carried over to subsequent queries.
The coherent operation methods supported by the system are:
Method
Function
Supported parameter types
where Used to query or update the definition of conditions Strings, arrays and objects
table Used to define the operations to be performed Data table name String and array
alias Used to define an alias for the current data table String
data Used to assign data objects before adding or updating data Arrays and objects
field Used to define the fields to be queried ( Supports field exclusion) Strings and arrays
order Used to sort results Strings and arrays
limit Used to limit the number of query results Strings and numbers
page Used for query paging (will be converted to limit internally) Strings and Number
group Used for group support for queries String
having Used for having support for queries String
join* Used for join support for queries Strings and arrays
union* Used for union for queries Support strings, arrays and objects
distinct Support for query distinct Boolean value
lock Lock mechanism for database Boolean value
cache For query cache Support multiple parameters (described in detail in the cache section later)
于Relation is used to associate inquiries (need to expand support) string. String, array All consecutive operations return the current model instance object (this), and the ones marked with * support multiple calls. UsageSince the use of coherent operations often involves the joint use of multiple methods, the basic usage of each coherent operation is briefly introduced below: WHERE where is used to query or update the definition of conditionsUsage where($where) Parameters where (required): query or operation conditions, supports strings, arrays and objects Return value Current model instance Remarks If the where method is not called, updates and deletions will not be performed by default Operation Where method is the most commonly used coherent operation method. For more detailed usage, please refer to: Quick Start (3) Query Language.
TABLE
table Define the name of the data table to be operated, and dynamically change the name of the data table for the current operation. You need to write the full name of the data table, including the prefix. You can use aliases and cross-database operations
Usage table($table)
Parameters table (required): Data table name, supports operating multiple tables, supports strings, arrays and objects
Return value Current model instance
Remarks If the table method is not called, the data table corresponding to or defined by the model will be automatically obtained
Usage example:
$Model->Table('think_user user')->where('status>1')->select();
You can also perform 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 strings and arrays. Usage in array mode:
$Model->Table(array('think_user'=>'user','think_group'=>'group'))->where('status>1')->select();
The advantage of using array definition is that it can avoid errors due to conflicts between table names and keywords.
Under normal circumstances, there is no need to call the table method. The data table corresponding to or defined by the current model will be automatically obtained by default.
DATA
data can be used to assign data objects before adding or saving data
Usage data($data)
Parameters data (required): data, supports arrays and objects
Return value Current Model instance
Remarks If the data method is not called, the current data object or the data passed in add and save will be taken
Usage example:
$Model->data($data)->add();
$Model->data($data)->where('id=3')->save();
The parameters of the Data method support objects and arrays. If they are objects, they will be automatically converted into arrays. If you do not define the data method to assign a value, you can also use the create method or manually assign a value to the data object.
In addition to creating data objects, the data method of the model can also read the current data object,
For example:
$this->find(3);
$data = $this->data() ;
FIELD
field Used to define the fields to be queried
Usage field($field,$except=false)
Parameters
field (required): field name, supports strings and arrays, Supports specifying field aliases; if true, it means explicit or all fields in the data table.
except (optional): Whether to exclude, the default is false, if true, it means that the defined fields are all fields in the data table except the field parameter definition.
Return value Current model instance
Remarks If the field method is not called, all fields will be returned by default, which is equivalent to field ('*')
Usage example:
$Model->field(' id,nickname as name')->select();
$Model->field(array('id','nickname'=>'name'))->select();
if If the field method is not called or the parameter passed in to the field method is empty, it is equivalent to using field ('*').
If you need to pass in all fields explicitly, you can use the following method:
$Model->field(true)->select();
But we recommend only getting the field names that need to be explicit , or defined by field exclusion, for example:
$Model->field('status',true)->select();
means to get all fields except status.
ORDER
order is used to sort the operation results
Usage order($order)
Parameters order (required): sorted field name, supports strings and arrays, supports multiple field sorting
Return value Current model instance
Remarks If the order method is not called, the default rules of the database will be followed
Usage example:
order('id desc')
The sorting method supports sorting of multiple fields
order('status desc,id asc')
The parameters of the order method support strings and arrays. The usage of arrays is as follows:
order(array('status'=>'desc','id'))
LIMIT
limit is used to define the limit of results to be queried (supports all database types)
Usage limit($limit)
Parameter limit (required): limit quantity, supports string
Return value Current model instance
Note If the limit method is not called, it means there is no limit
Note: If the limit method is not called, it means there is no limit.
We know that the usage of limit is different for different database types, but the usage in ThinkPHP is always a unified method, that is, limit('offset,length') , whether it is Mysql, SqlServer or Oracle database, it is used in this way, and the database driver class of the system will be responsible for solving this difference.
Usage example:
limit('1,10')
can also be written in the following way, which is equivalent:
limit(1,10)
If you use
limit('10')
Equivalent to
limit('0,10')
PAGE
page is used to define the data paging to be queried
Usage page($page)
Parameters page (required): paging, supported String
Return value Current model instance
Remarks None
Page operation method is a new feature, which can perform paging query more quickly. The usage of the
Page method is similar to the limit method. The format is:
Page('page[,listRows]')
Page represents the current number of pages, and listRows represents the number of records displayed on each page. For example:
Page('2,10')
means that when 10 records are displayed on each page, the data on page 2 is obtained.
The following writing method is equivalent:
Page(2,10);
listRow will read the value of limit('length') if not written, for example:
limit(25)->page(3 );
means that when 25 records are displayed on each page, the data on page 3 is obtained.
If limit is not set, the default is to display 20 records per page.
The page method adds support for a second parameter, for example:
$this->page(5,25)->select();
and previous usage
$this->limit('5, 25')->select();
equivalent.
GROUP
group group query support for database
Usage group($group)
Parameters group (required): field name of group, supports string
Return value Current model instance
Remarks None
Usage example:
group('user_id')
Group method parameters only support strings
HAVING
having for database having query support
Usage having($having)
Parameters having (required): having, supports strings
Return value Current model instance
Remarks None
Usage example:
having('user_id>0')
having method parameters only support strings
JOIN
join for database join query support
Usage join($join)
Parameters join (required): join operation, supports strings and arrays
Return value Current model instance
Remarks The join method supports multiple calls
Usage example:
$Model->join(' work ON artist.id = work.artist_id')->join('card ON artist.card_id = card.id')- >select();
The default method is LEFT JOIN. If you need to use other JOIN methods, you can change it to
$Model->join('RIGHT JOIN work ON artist.id = work.artist_id')-> ;select();
If the parameters of the join method are arrays, the join method can only be used once, and it cannot be mixed with string methods.
For example:
join(array('work ON artist.id = work.artist_id','card ON artist.card_id = card.id'))
UNION
union union query support for database
Usage union($union,$all=false)
Parameters union (required): union operation, supports strings, arrays and objects
all (optional): whether to use UNION ALL operation, the default is false
Return value Current model instance
Remarks Union method supports multiple calls
Usage example:
$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'))
. 'name')
->table('think_user_0')
-->union(array('SELECT name FROM think_user_1','SELECT name FROM think_user_2'))
->select();
Supports UNION ALL operations, such as:
$Model->field('name')
->table('think_user_0')
- ->union('SELECT name FROM think_user_1',true)
- >union('SELECT name FROM think_user_2',true) ->select(); ;-& GT; Union (Array ('Select name from Think_user_1', 'Select name from Think_user_2'), True)-& GT; Select (); Essence
Note: The SELECT statements inside the UNION must have the same number of columns. Columns must also have similar data types. Also, the order of the columns in each SELECT statement must be the same. DISTINCT distinct performs unique filtering when querying data Usage distinctct($distinct) Parameter distinct (required): Whether to use distinct, supports Boolean value Return value Current model instance Remarks None Usage example:
$Model->Distinct(true)->field('name')->select();
LOCK
lock is used for query or write lock
Usage Lock($lock)
Parameters Lock (required): Whether locking is required, supports Boolean value
Return value Current model instance
Remarks The join method supports multiple calls
Lock method is a lock mechanism for the database , if used when querying or executing operations:
lock(true)
will automatically add FOR UPDATE or FOR UPDATE NOWAIT (Oracle database) at the end of the generated SQL statement.
VALIDATE
validate is used for automatic verification of data
Usage Validate($validate)
Parameters validate (required): Automatic verification definition
Return value Current model instance
Remarks Can only be used with the create method Used in conjunction with the
validate method for automatic verification of data, we will describe it in detail in the data verification section.
AUTO
auto is used for automatic data completion
Usage auto($auto)
Parameters auto (required): Define automatic completion
Return value Current model instance
Remarks au The to method can only be used with create Method Usage The
auto method is used for automatic completion of data. The specific use will be described in the data automatic completion section.
SCOPE
scope is used for the named scope of the model
Usage Scope($scope)
Parameters Scope (required): Named scope definition
Return value Current model instance
Remarks Scope method is actually coherent Pre-definition of operations
scope method specific usage can refer to: 3.1’s new feature named scope
FILTER
filter is used for safe filtering of data
usage filter($filter)
parameter filter (required ): Filter method name
Return value Current model instance
Remarks The filter method is generally used for write and update operations
filter method is used for safe filtering of data objects, for example:
$Model->data($ data)->filter('strip_tags')->add();
Currently the filter method does not support filtering by multiple methods.
Summary
Coherent operations bring great convenience to our data operations, and as long as operations that can be achieved by SQL can basically be implemented by ThinkPHP's coherent operations, there is no need to consider the expression between databases Difference, portability. I will explain to you how to operate and obtain variables later.
The above is the content of ThinkPHP3.1 quick start (4) coherent operation. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

We start this series by learning how to animate HTML elements using mojs. In this second tutorial, we continue using the Shape module to animate built-in SVG shapes. The third tutorial covers more ways to animate SVG shapes using ShapeSwirl and the stagger module. Now we will learn how to animate different SVG shapes in bursts using the Burst module. This tutorial will depend on the concepts we introduced in the previous three tutorials. If you haven't read them yet, I recommend reading them first. Creating a Basic Burst Animation The first thing we need to do before creating any burst animation is to instantiate a Burst object. Afterwards, we can specify different properties

Quick Start: How to install the pandas library in Python requires specific code examples 1. Overview Python is a widely used programming language with a powerful development ecosystem that includes many practical libraries. Pandas is one of the most popular data analysis libraries. It provides efficient data structures and data analysis tools, making data processing and analysis easier. This article will introduce how to install the pandas library in Python and provide corresponding code examples. 2. Install Py

Quick Start: Implementing a Simple Audio Streaming Service Using Go Language Functions Introduction: Audio streaming services are becoming more and more popular in today's digital world, which allow us to play audio files directly over the network without performing a complete download. This article will introduce how to use Go language functions to quickly implement a simple audio streaming service so that you can better understand and use this function. Step 1: Preparation First, you need to install the Go language development environment. You can download it from the official website (https://golan

Quick Start: Use Go language functions to implement simple image recognition functions In today's technological development, image recognition technology has become a hot topic. As a fast and efficient programming language, Go language has the ability to implement image recognition functions. This article will provide readers with a quick start guide by using Go language functions to implement simple image recognition functions. First, we need to install the Go language development environment. You can download the appropriate version on the Go language official website (https://golang.org/)

Title: Get Started Quickly: Recommended Five Common Go Language Frameworks In recent years, with the popularity of the Go language, more and more developers have chosen to use Go for project development. The Go language has received widespread attention for its efficiency, simplicity and superior performance. In Go language development, choosing a suitable framework can improve development efficiency and code quality. This article will introduce five commonly used frameworks in the Go language, and attach code examples to help readers get started quickly. Gin framework Gin is a lightweight web framework that is fast and efficient.

Quick Start: A Guide to Using Five Kafka Visualization Tools 1. Kafka Monitoring Tools: Introduction Apache Kafka is a distributed publish-subscribe messaging system that can handle large amounts of data and provide high throughput and low latency. Due to the complexity of Kafka, visualization tools are needed to help monitor and manage Kafka clusters. 2.Kafka visualization tools: five major choices KafkaManager: KafkaManager is an open source web community

Quick Start: Use Go language functions to implement simple data visualization line chart display Introduction: In the field of data analysis and visualization, line charts are a commonly used chart type that can clearly show the trend of data changes over time or other variables. This article will introduce how to use Go language functions to implement a simple data visualization line chart display, and provide relevant code examples. 1. Before starting the preparation work, you need to ensure the following conditions: install the Go language environment and set the relevant environment variables. Install necessary dependencies

Quick Start: Use Go language functions to implement simple message push functions In today's mobile Internet era, message push has become a standard feature of various APPs. Go language is a fast and efficient programming language, which is very suitable for developing message push functions. This article will introduce how to use Go language functions to implement a simple message push function, and provide corresponding code examples to help readers get started quickly. Before we begin, we need to understand the basic principles of message push. Generally, message push functionality requires two main components: push server
