Meaning: The View in this article refers to the database View model, rather than the View class in ThinkPHP to implement the ThinkPHP database View model.
Note: The View in this article refers to the database View model, rather than the View in ThinkPHP.
View class implementation.
A database View is a virtual table that extracts the required data columns from one or more basic tables as needed. In this way, you do not have to query Table B and Table c based on table.
Tables.
Views are not supported in some databases. ThinkPHP
Simulate and implement the database view, which can be used for multi-table joint query.
To use the View model in ThinkPHP, you only need to inherit the ViewModel and then set
ViewFields attribute. use the D method to instantiate the model.
View model instance
The existing user table and article table are as follows (the table prefix is
Test _):
User table (omitted ):
Article table (omitted ):
Create a View model file
-
- Class ArticleViewModel extends ViewModel {
- Public $ viewFields = array (
- 'Article' => array ('aid ', 'title', 'content', 'uid '),
- 'User' => array ('username', '_ on' => 'article. uid = user. uid '),
- );
- }
- ?>
In this view model file, the model class inherits the ViewModel
View model and define $ viewFields attributes. each element includes a data table and the fields to be queried. In each table element
Element to define the association query conditions.
Save the file as Lib/Model/ArticleViewModel. class. php.
In the Action
Use View model in operation
In module operations, use the D method to instantiate the View model:
-
- Class ArticleAction extends Action {
- Public function index (){
- Header ("Content-Type: text/html; charset = utf-8 ");
- $ Dao = D ('articleview'); // instantiate the View
- $ Article_list = $ Dao-> select ();
- Print_r ($ article_list );
- Echo'
';
- // Print the executed SQL statement
- Echo: '. $ Dao-> getLastSql ();
- }
- }
- ?>
Access this method and print the result as follows:
- Array
- (
- [0] => Array
- (
- [Aid] => 1
- [Title] => Article 1
- [Content] => Article 1 details ......
- [Username] => admin
- )
- [1] => Array
- (
- [Aid] => 2
- [Title] => Article 2
- [Content] => Article 2 details ......
- [Username] => Jack
- )
- )
The executed SQL statement is:
- SELECT article. aid AS aid, article. title AS title, article. content AS content,
- Article. uid AS uid, user. username AS username FROM test_article article JOIN test_user user ON
- Article. uid = user. uid
From the above results, we can see that the view model simulates the implementation of the database view by using JOIN queries to aggregate data from multiple tables.