Home Backend Development PHP Tutorial ThinkPHP view query

ThinkPHP view query

Jun 06, 2018 pm 03:05 PM
thinkphp

This article mainly introduces ThinkPHP view query. Friends who need it can refer to it

The view query application function provided by ThinkPHP is very powerful. Users can use the view query function to sort the field contents of multiple data tables by It needs to be specified and filtered, organized into a view model based on these data tables, and then multi-table joint queries can be directly performed through the model, which is very convenient and simple.

For example, in the project, we have three tables defined:

##user User basic table,

user_info User details table,
dept Department classification table

Now we need to obtain a certain user information.

This information should include the user's account name and related information and the name of the department.
At this time we can use view query to process.

The following examples are given to illustrate:

1. Build a new project and perform related configurations (refer to the previous tutorial, omitted here)

2. Create a database tpview, and add this Three tables
(1) User table

CREATE TABLE `think_user` (
 `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID编号',
 `name` varchar(20) NOT NULL COMMENT '帐户',
 `password` varchar(32) NOT NULL COMMENT '密码',
 `dept_id` smallint(6) unsigned NOT NULL,
 `status` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '开放状态',
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='会员表' AUTO_INCREMENT=2 ;
INSERT INTO `think_user` (`id`, `name`, `password`, `dept_id`, `status`) VALUES
(1, 'zzguo28', '123456', 2, 1);
Copy after login

(2) User information

CREATE TABLE `think_user_info` (
 `user_id` int(11) NOT NULL COMMENT '用户id',
 `nick_name` varchar(30) NOT NULL COMMENT '用户昵称',
 `email` varchar(100) NOT NULL COMMENT '邮箱地址',
 `address` varchar(100) NOT NULL COMMENT '详细地址',
 `gender` tinyint(1) NOT NULL DEFAULT '0' COMMENT '性别',
 `mobile` varchar(100) NOT NULL COMMENT '手机号码',
 `telephone` varchar(100) NOT NULL COMMENT '电话号码',
 KEY `user_id` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='用户信息表';
INSERT INTO `think_user_info` (`user_id`, `nick_name`, `email`, `address`, `gender`, `mobile`, `telephone`) VALUES
(1, '国', 'zzguo28@163.com', 'TP路think街1.6号', 1, '12345678901', '123456');
Copy after login

(3) Department classification table

CREATE TABLE `think_dept` (
 `id` smallint(3) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
INSERT INTO `think_dept` (`id`, `name`) VALUES
(1, '开发部'),
(2, '销售部'),
(3, '财务部');
Copy after login

3. In project/Lib/ Create the basic model Model

of these three tables under Model. This example does not involve verification and other functions, so it can be tested simply by defining it, for example

 <?php
  class UserModel extends Model {
  }
 ?>
Copy after login

In fact, the data table corresponding to the view model does not necessarily have to be Corresponding basic model, but it is recommended that you create it so that both single tables and views can operate.

4. Create a view model, the code is as follows, detailed annotations are shown below:


(Note: The latest svn has added the function of dynamically extending the model. To use the new version, you need to change the protected attribute to public attribute. , it is recommended to use the dynamic expansion function to use view queries instead of the inheritance method in this tutorial. That way it will be more flexible.)

<?php
import(&#39;ViewModel&#39;);
class UserViewModel extends ViewModel{
  protected $viewFields = array(
    &#39;User&#39;   =>array(&#39;id&#39;,&#39;name&#39;,&#39;_as&#39;=>&#39;u&#39;,&#39;_type&#39;=>&#39;left&#39;),
    &#39;UserInfo&#39; =>array(&#39;email&#39;,&#39;mobile&#39;,&#39;_as&#39;=>&#39;ui&#39;,&#39;_on&#39;=>&#39;ui.user_id=u.id&#39;),
    &#39;Dept&#39;   =>array(&#39;name&#39;=>&#39;dept&#39;,&#39;_on&#39;=>&#39;u.dept_id=Dept.id&#39;),
  );
}
?>
Copy after login

The above code is explained as follows:

In Chapter 2 In the line of code, since the view query has been separated from the original Model class since TP version 1.6, the view model class needs to be introduced here using the import method.

In the third line of code, the model name is defined as UserViewModel. The name before the view model Model is arbitrary, just to distinguish it from other models. Usually we will name it in such a way as xxxViewModel . And must inherit ViewModel. (ThinkPHP version 1.6 no longer needs to set the viewModel attribute of the model to true, as long as it inherits ViewModel)

The $viewFields attribute in line 4 of the code represents the fields contained in the view model. Each element defines each data table or Fields required by the model.

The format is

protected $viewFields = array(
    &#39;表名&#39;=>array(&#39;所需字段&#39;,&#39;_as&#39;=>&#39;别名定义&#39;,&#39;_on&#39;=>&#39;筛选条件&#39;,&#39;_type&#39;=>&#39;指定join类型,支持right,inner,left三种&#39;),
);
Copy after login

Note that 'name'=>'dept' in the 7th line of code, because there is already a name field in the User model, so we use this method to add the Dept model The name field is mapped to the dept field. If there are multiple fields, they can be added in the same way.

After the definition is completed, we test it in Action. The code is as follows

<?php
class IndexAction extends Action{
  public function index(){
    $dao = D(&#39;UserView&#39;);
    $where[&#39;u.id&#39;] = 1;
    dump($dao->where($where)->find());
    dump($dao->getLastSql());
  }
}
?>
Copy after login

Then access the operation and you can see that we successfully obtained the required query content:

array(1) {
 [0] => array(5) {
  ["id"] => string(1) "1"
  ["name"] => string(7) "zzguo28"
  ["email"] => string(17) "zzguo28@163.com"
  ["mobile"] => string(11) "12345678901"
  ["dept"] => string(9) "销售部"
 }
}
Copy after login

And you can see that the sql used is as follows

"SELECT u.id AS id,u.name AS name,ui.email AS email,ui.mobile AS mobile,Dept.name AS dept FROM think_user u LEFT JOIN think_user_info ui ON ui.user_id=u.id JOIN think_dept Dept ON u.dept_id=Dept.id WHERE ( u.id = 1 ) LIMIT 1 "
Copy after login

The view model is not much different from the ordinary single table in querying. You can use various coherent operations that we are familiar with, such as order, limit etc.

Related recommendations:

Behavior extensions and plug-ins in ThinkPHP

ThinkPHP implementation update data example detailed explanation (demo)

The above is the detailed content of ThinkPHP view query. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

See all articles