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
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.
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);(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');(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, '财务部');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 { } ?>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('ViewModel'); class UserViewModel extends ViewModel{ protected $viewFields = array( 'User' =>array('id','name','_as'=>'u','_type'=>'left'), 'UserInfo' =>array('email','mobile','_as'=>'ui','_on'=>'ui.user_id=u.id'), 'Dept' =>array('name'=>'dept','_on'=>'u.dept_id=Dept.id'), ); } ?>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( '表名'=>array('所需字段','_as'=>'别名定义','_on'=>'筛选条件','_type'=>'指定join类型,支持right,inner,left三种'), );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('UserView'); $where['u.id'] = 1; dump($dao->where($where)->find()); dump($dao->getLastSql()); } } ?>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) "销售部" } }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 "
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor