ThinkPHP model details

Source: Internet
Author: User
This article mainly introduces the ThinkPHP Model details. For more information, see the Model definition. by default, the ThinkPHP Model class is located under the/Home/Model/directory, the Model class usually needs to inherit the system's \ Think \ Model class or its subclass. The following is the definition of a Home \ Model \ UserModel class:

The file name follows the UserModel. class. php method, which is the same as the controller name.

<?phpnamespace Home\Model;use Think\Model;class UserModel extends Model {}

The role of a model class is to operate data tables. if a model class is named according to system specifications, data tables can be automatically matched in most cases, however, you can customize data table settings and operations as needed.

First, we need to set our database connection information in the configuration file:

  'DB_TYPE'        => 'mysql',     'DB_HOST'        => 'localhost',   'DB_NAME'        => 'database',    'DB_USER'        => 'username',     'DB_PWD'        => 'password',    'DB_PORT'        => '3306',   

The configuration information is still set in the/Home/Conf/config. php file.

Data table prefix

Indicates the calibration prefix. we have specified the configuration items in the first lesson. the following text indicates that you can flexibly configure your data table.

protected $tablePrefix = 'top_';

If the database table does not have a table prefix, use a null string instead.

protected $tablePrefix = '';

Specify a data table. you do not need to add a table prefix for the specified data table here:

protected $tableName = 'user';

For example, if your database has a data table named users without a table prefix, you can use the following two methods to define it in the model:

First, name the model class directly according to the system specifications. for example, to name UsersModel, you only need to add the following settings in the class:

protected $tablePrefix = '';

The ThinkPHP system will automatically locate the users table.

In the second case, if your model class is not named according to the system specification, for example, you may accidentally name it UserModel. in this case, you can specify the table prefix and representation at the same time, for example:

protected $tablePrefix = '';protected $tableName = 'users';

Or you can directly specify trueTableName:

Protected $ trueTableName = 'users ';

Since the model is usually used to operate data tables, let's look at the basic CURD of the model:

Note: To facilitate the demonstration, we define a testDemo () method in UserController for demonstration.

public function testDemo()  {  }

The following code will be demonstrated in this method for a while. you can see the actual effect by accessing http: // localhost: 8999/index. php/Home/User/testDemo.

Add record

$user = M('User');$data['username'] = 'ThinkPHP';$data['email'] = 'ThinkPHP@gmail.com';$user->create($data);$record = $user->add();dump($record);

Add () returns the id of the inserted data. the add () method automatically filters out non-existing table fields.

Read records

There are many ways to read data in ThinkPHP: reading data, reading data sets, and reading field values.

$user = M('User');$record = $user->where('username="ThinkPHP"')->find();dump($record);

Read field value

$user = M('User');$record = $user->where('id=3')->getField('username');dump($record);

By default, when there is only one field, the value of the first row of the field in the data table that meets the conditions is returned. if getField () is input into multiple fields, the returned value is an associated array:

$user = M('User');$record = $user->getField('username,email');dump($record);

This array always uses the first input field as the key value. If Changed:

$user = M('User');$record = $user->getField('email,username');dump($record);

Put the above two codes to testDemo () respectively, and you will see different result sets.

Update data using the save () method

$user = M('User');$data['username'] = 'ThinkPHPSave';$data['email'] = 'ThinkPHPSave@outlook.com';$record = $user->where('id=3')->save($data);dump($record);

1 returned by $ record indicates successful modification.

You can also:

$user = M('User');$user->username = 'ThinkPHP';$user->email = 'ThinkPHP@outlook.com';$record = $user->where('id=3')->save();dump($record);

During daily development, you will often encounter some situations where only some fields are updated, which can be achieved through the following methods:

$user = M("User"); $record = $user->where('id=4')->setField('username','ThinkPHPChangeName');dump($record);

Update multiple fields at the same time. you can pass the data in the form of an array to the setField () method:

$user = M('User');$data = array('username'=>'ThinkPHPChangeArray','email'=>'ThinkPHP@array.com');$record = $user-> where('id=6')->setField($data);dump($record);

ThinkPHP uses the delete method to delete data, for example:

$user = M('User');$record = $user->where('id=3')->delete();dump($record);

Or you can directly use:

$record = $user->delete('1,2,5');dump($record);

In this way, the records of primary keys 1, 2, and 5 are deleted.

ActiveRecords

ThinkPHP implements the ActiveRecords mode ORM model and adopts a non-standard ORM model: tables are mapped to classes, and records are mapped to objects. The following example uses ActiveRecords to reproduce the CURD of the data table to see what benefits ActiveRecords bring to us.

$user = M("User");$user->username = 'ThinkPHPWithActive';$user->email = 'ThinkPHPActive@gmail.com';$record = $user->add();dump($record);

Read records

The most important feature of AR is probably its query mode, which is easy to use, because in more cases, the query conditions are based on the primary key or a key field. ThinkPHP supports this type of query.

For example, to obtain user information with the primary key of 2:

$user = M("User");$record = $user->find(2);dump($record);

You don't need to query where () directly. it's simple and friendly. For example:

$user = M("User");$record = $user->getByUsername("jelly");dump($record);

To query multiple records, use the following method:

$user = M("User");$record = $user->select('1,3,8');dump($record);

Update record

$user = M("User");$user->find(21);$user->username = 'TOPThinkChangeWithAR';$record = $user->save();dump($record);

Delete record

Delete a single record

$user = M("User");$record = $user->delete(8);dump($record);

Delete multiple records

$ User = M ("User"); $ record = $ user-> delete ('15, 16'); dump ($ record); // todo: automatic verification and associated model debugging cannot be performed here.

Automatic Completion

Automatic completion is a method provided by ThinkPHP to automatically process and filter data. when you create a data object using the create () method, the automatic completion mechanism is triggered.

Therefore, we recommend that you use the create () method to create data objects in ThinkPHP, because this is a safer method, directly by adding () or save () method to implement the automatic completion mechanism for data writing.

Automatic completion is usually used to write default fields (such as adding timestamps), filter security fields (such as encrypted passwords), and automatically process business logic. You can define processing rules using the $ _ auto attribute in the model class. The following shows how to add a timestamp automatically:

In UserModel, declare the automatically completed definition array $ _ auto:

protected $_auto = array (    array('created_at','date("Y-m-d H:i:s", time())',3,'function'),    array('updated_at','date("Y-m-d H:i:s", time())',3,'function'),  );

Another reason is that the auto () method dynamically sets the automatic completion mechanism. you can go to the official documentation to see it.

After the settings are complete, we create a user data in the testDemo () method:

$user = D('User');$data['username'] = "ThinkPHP";$data['email'] = "ThinkPHP@gmail.com";$user->create($data);$record = $user->add();dump($record);

Test. if the id value of the record is returned, the user record is successfully created. To verify whether the data is automatically completed, you can directly use:

$user = D('User');$record = $user->find(id);dump($record);

Automatic Verification

Automatic verification is a data verification method provided by the ThinkPHP model layer. you can automatically perform data verification when using create () to create a data object.

Data verification can be performed on data types, business rules, and security judgments.

Usually used for form verification

There are two ways to verify data:

Static Mode: use the $ _ validate attribute to define verification rules in the model class.

Dynamic mode: use the model class's validate () method to dynamically create automatic verification rules.

Regardless of the method, the Verification rule is defined as a unified rule in the following format:

Array (
Array (verification field 1, verification rules, error prompt, [verification conditions, additional rules, verification time]),
Array (verification field 2, verification rules, error prompt, [verification conditions, additional rules, verification time]),
......
);
The following uses the $ _ validate static method as an example to show how to use automatic verification:

Create the register () method in UserController. Yes, almost every Web application needs to implement user registration.

public function register()  {    $this->display();  }

Yes, it is so simple. this method only renders the corresponding view file. So next we will create the corresponding View file, that is:./Application/Home/View/User/register.html

 
 

The above is some HTML code and a little template knowledge. we will talk about the template later, but no matter what, now we visit
Http: // localhost: 8999/Home/User/register, you can see our registry form page.

Note that in the form, action = "/index. php/Article/registerValidate ", which indicates that it is submitted to the current controller's registerValidate () method for processing, so we add the registerValidate () method in UserController:

public function registerValidate()  {    $data['username'] = $_POST['username'];    $data['email'] = $_POST['email'];    $user = D("User");    if ( !$user->create($data) ) {      exit($user->getError());    }    //todo: validation passes, add data to database and redirect somewhere    echo 'validation passes';  }

If (! $ User-> create ($ data) triggers automatic verification and determines whether the verification is successful. You can enter different data in the form for testing, or modify the verification rules. for more rules, visit the official website:

Http://document.thinkphp1.cn/manual_3_2.html#auto_validate

Associate model

Generally, the join relationship includes the following three types:

One-to-one association: ONE_TO_ONE, including HAS_ONE and BELONGS_TO
One-to-multiple Association: ONE_TO_MANY, including HAS_MANY and BELONGS_TO
Many-to-many association: MANY_TO_MANY

Association definition

ThinkPHP can easily associate data tables with CURD. Currently, the following four associations are supported:
HAS_ONE, BELONGS_TO, has_detail, and many_to_detail.
A model can define multiple associations at the same time based on the complexity of the business model without restrictions. all association definitions are defined in the $ _ link member variables of the model class, dynamic definition is also supported. To support association operations, the Model class must inherit the Think \ Model \ RelationModel class. the format of the Association definition is similar:

Namespace Home \ Model; use Think \ Model \ RelationModel; class UserModel extends RelationModel {protected $ _ link = array ('association' => array ('Association attribute 1' => 'define ', 'correlated property n' => 'define ',),);}

For the definition and value of association attributes, you can go to the official documentation for a closer look. below we will also provide some of the most commonly used.

In our example, HAS_MANY and BELONGS_TO will be used for demonstration. for other relational models, refer to the official document to draw a line between them.

First, we know that the database has two tables, user table and article table, and we have created different models for them (UserModel ArticelModel ).

Now let's take a closer look at the relationship between them: a user can have multiple articles, and each article belongs to a specific user. Therefore, we can add an association model for these two relationships:

In UserModel:

protected $_link = array(    'Article' => self::HAS_MANY  );

In ArticleModel:

protected $_link = array(    'User' => self::BELONGS_TO  );

Both of the above are the most concise model Association declarations. When we first designed the database, we followed the official ThinkPHP specifications:

The default rule for foreign keys is the name _ id of the current data object. for example, if UserModel corresponds to the think_user table, the foreign key of the think_user table is user_id by default, if your foreign key is not user_id but other custom fields such as user_identify, you must define foreign_key when defining the association. As follows:

In UserModel:

protected $_link = array(    'mapping_type' => self::HAS_MANY,    'class_name'  => 'Article',    'foreign_key'  => 'user_identify',  );

For more custom associated model parameters, visit the official website.

With the above definition, we can retrieve the user data together with his articles and use relation ().

It is also in the testDemo () method:

$user = D('User');$record = $user->relation(true)->find(4);dump($record);

Visit the familiar http: // localhost: 8999/Home/User/testDemo and you will see the amazing results.

The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.