Home >Backend Development >PHP Tutorial >Detailed explanation of view model in ThinkPHP., thinkphp view_PHP tutorial
Many TP novices do not know much about the view model in the model. Although the official manual has a detailed manual, it is not suitable for beginners. It’s still hard to understand!
First, let’s briefly talk about the functions that the view model can achieve. Basically, it is the association of various fields between the main table and the secondary table. It is much simpler to implement multi-table association queries than using native SQL statements. .
First of all, when initializing the data table, instead of using the traditional M ('User'), D ('UserView') is used in the view model, as shown below:
The main thing that needs to be capitalized is the first letters of several words.
Then create a new name in the Lib/Model directory named XXXViewModel.class.php (XXX is any controller name/the first letter is capitalized). The content format inside is as follows:
It is recommended to add '_type'=>'LEFT' after all arrays. Because when the data of the associated table is empty, the system will report an error.
First of all, the main table is the field that needs to be queried in the customer array. The p_id and b_id inside are the aliases of the table settings it is associated with. In fact, it is similar to the LeftJoin statement in native SQL.
As shown in the picture above, '_table' writes the name of the table you need to associate. It is worth noting that the full name of the table needs to be written, including its prefix.
‘_as’ is the alias you want to give it, ‘name’ is the field you will use later when performing CURD operations,
‘_on’ performs the association operation: main table. The associated ID = secondary table (alias is used). Primary key ID. When they are equal, a certain field of the main table and a certain field of the secondary table are realized. The pieces of data are associated, and the Select operation is finally awakened to display the associated content.
Of course, this is generally used to deal with overly complicated table data relationships. For example, a main table is associated with more than a dozen subsidiary tables. In this case, you will feel less worried when using the view model.
This is just a simple example of basic functions, which is basically explained here. I hope it can help some TP novices.
It depends on your preferences and habits
'cate'=>array('id','name'),
'Category'=>array('count(*)'=>'nums', '_on'=> 'blog.cid=cate.id'),