ThinkPHP model definition and thinkphp Model
The Model class is generally located under the Lib/Model directory of the Project. When we create a UserModel class, we have actually followed the system conventions. The naming rule for Model classes is to remove the table prefix from the table name. The data table names are named using the hump method, and the first letter is capitalized. Then, the Model class suffix is added to define the Model. For example:
Model name (class name) |
Specify the corresponding data table (assume that the database prefix is defined as think _) |
UserModel |
Think_user |
UserTypeModel |
Think_user_type |
If your rules do not match the above system conventions, you need to set the data table name attribute of the Model class.
In the ThinkPHP model, there are several attribute definitions about data table names:
Attribute |
Description |
TableName |
The name of a data table that does not contain the table prefix. Generally, it is the same as the model name by default. It must be defined only when your table name and the current model class name are different. |
TrueTableName |
The name of the data table containing the prefix, that is, the actual table name in the database. This name does not need to be set. It must be set only when none of the preceding rules apply or in special circumstances. |
DbName |
Define the name of the database corresponding to the model. This parameter must be defined only when the database name corresponding to your current model class is different from the configuration file. |
For example, there is a think_categories table in the database, and the model class name we define is CategoryModel. According to the system conventions, the model name is Category, the corresponding data table name should be think_category (all in lower case), but the current data table name is think_categories, therefore, we need to set the tableName attribute to change the default rule (assuming we have defined DB_PREFIX as think _ in the configuration file _).
- Protected $ tableName = 'category ';
Note that the table prefix think _ is not required for the definition of this attribute _
In another special case, the database has a table (top_depts) with a different prefix than other table prefixes, instead of think _ But top _. In this case, we need to define the trueTableName attribute.
- Protected $ trueTableName = 'top _ depts ';
Note that trueTableName requires a complete table name definition.
In addition to data table definitions, you can also define databases, for example:
- Protected $ dbName = 'top ';
4