Definition and application of THINKPHP5 Association model

Source: Internet
Author: User
Tags naming convention
Defining one-to-one associations

This assumes that you have configured the THINKPHP5 environment and that the database is connected to OK. You want to correlate the two tables with the model, and then you can get two-table information by calling the controller.
Now I have two tables, an administrator table pwn_admin an Administrator information table Pwn_admin_message to make it easier to understand, I posted the table structure of both tables.
Here is the table structure information for the two tables:

CREATE TABLE ' pwn_admin ' (
  ' id ' int (6) NOT NULL auto_increment,
  ' user ' varchar ' is not null DEFAULT ',
  ' PASSW Ord ' varchar ' is not null default ',
  ' name ' varchar ' is not null default ',
  PRIMARY KEY (' id ')
engine=myis AM auto_increment=28 DEFAULT Charset=utf8;
CREATE TABLE ' pwn_admin_message ' (
  ' id ' int (6) NOT NULL auto_increment,
  ' email ' varchar ' is not null DEFAULT ', 
   ' mobile ' varchar NOT NULL default ',
  ' aid ' int (one) not null default ',
  PRIMARY KEY (' id ')
engin E=myisam auto_increment=1 DEFAULT Charset=utf8;
Build Model Files

The next step is to create a new model class file that corresponds to two data tables. Create a new model directory under the module and create a new two files and name them according to the corresponding table:
model naming

The naming convention for model classes is the name of the datasheet that removes the table prefix, named after the hump, and uppercase, such as the table prefix for the two tables above, which needs to be omitted from the Pwn_ in the model name. So the model class name of the Pwn_admin table is admin, Pwn_admin_message's model class name is Adminmessage

The parameters of the Hasone method include:

Hasone (' Association model name ', ' foreign Key name ', ' primary key name ', [' model alias definition '], ' join type ');

The default join type is the inner model definition

The admin model corresponds to the Pwn_admin table

<?php
namespace App\index\model;

Use Think\model;
Class Admin extends model{

    function adminmessage () {
        //aid as foreign key ID is the foreign key adminmessage table associated Admin table and the admin table's
        primary key return
        $this->hasone (' adminmessage ', ' aid ', ' id ')->field (' Id,coltype,auth,name,intro,xuhao,pid,pname ') ;
    }
}


? >

After the admin model has defined the associated method, it is not possible to write any corresponding method in the Adminmessage model, but it must have at least one empty model corresponding to the Pwn_admin_message table.
Accordingly, if it is written in this model,

<?php
namespace App\index\model;

Use Think\model;
Class Adminmessage extends model{


}
?>

One thing to note is that the association method of the naming code is the Hump method, and the associated property is generally lowercase + underlined way, the system will automatically convert the corresponding when the acquisition, read User_profile Association properties of the corresponding association method should be userprofile. Controller Call

When the controller wants to use the association model, it needs to introduce the model class first, for example, I have defined the method of association in the admin model, so I need to introduce the admin model into the controller.

Use App\index\model\admin

<?php
namespace App\index\controller;
Use Think\controller;
Use App\index\model\admin;

Class Index extends Controller
{
    /**
     * @param string $name
    /Public Function index ($name = ' Name ')
    {
        //get 1 is to get the data
        //find () with ID 1 () is
        to find//toarray ()  is the data obtained into the array
       $admin = Admin::get ( 1);
    Var_dump ($admin->find ()->toarray ());
    >

All right, now you can visit the following browsers to see the results.

If your results are so only the admin admin table data, don't worry it's normal. If you want to get data to the associated table pwn_admin_message, you need to first call the Adminmessage () model method that you just defined, and then remove the data in the point find () method.
Note:
This find () method can not be omitted from the oh, I just because this method is not added so I have been unable to take out the full administrator information.

<?php
namespace App\index\controller;
Use Think\controller;
Use App\index\model\admin;

Class Index extends Controller
{
    /**
     * @param string $name
    /Public Function index ($name = ' name ') c10/>{
       $admin = admin::get (1);
       Query out the Pwn_admin_message table aid to 1 of a data, and then turn the array.
       $admin = $admin->adminmessage->find ()->toarray ();  
        Var_dump ($admin);
  >

The result is

Because it is the test for convenience I do not use digital numbers, directly with the text code so more intuitive and clear.

Haswhere () Method: If you want to query the data for the current model based on the query criteria for the associated table, you can use the Haswhere method, for example:

<?php
namespace App\index\controller;
Use Think\controller;
Use App\index\model\admin;

Class Index extends Controller
{
    /**
     * @param string $name
    /Public Function index ($name = ' name ') c9/>{
        $admin =admin::haswhere (' adminmessage ', [' email ' => ' guanliB@ggg.com ']);
        $admin = $admin->find ()->toarray ();
        Var_dump ($admin);
    >

Output results:

Define a One-to-many association

The use of a One-to-many association and a one-to-one association is almost the same, except that the method name is different. A One-to-many method used in the model name is Hasmany. Hasmany and Hasone use the same methods and parameters.

The Hasmany parameters are:

Hasmany (' Association model name ', ' foreign Key name ', ' primary key name ', [' model alias definition ']);

Take the above two tables for example, but in order to match the content of a One-to-many association Pwn_admin_message and the aid field needs to be slightly modified. Change to an administrator has more than one cell phone number, there are multiple email mailboxes.
For the sake of understanding, I took a screenshot of the data contents of the two tables.
The following figure is the contents of the Pwn_admin_message table:

The following figure is the contents of the Pwn_admin table:

There are a few administrators who don't have the data, but it doesn't matter enough to test it. Okay, no more nonsense, start to get to the point.
I believe you can see that the following is the content of the admin model, corresponding to the Pwd_admin table

<?php
namespace App\index\model;

Use Think\model;
Class Admin extends model{

 public   function Adminmessage () {
        //pid as foreign Key ID is a foreign key to the Admin table associated with the Adminmessage table
        ID is the admin table's primary key return
        $this->hasmany (' adminmessage ', ' aid ', ' id ');
    }

And this is the following is adminmessage corresponds to which table I will not say. This can be an empty model as well as a one-to-one association.

<?php
namespace App\index\model;
Use Think\model;

Class Adminmessage extends model{/
    *    
    function Admin () {return
      $this->belongsto (' Admin ', ' aid ', ' ID ' );
    }
    */
}
?>

Controller call, this time is a bit different. Because the returned data is a two-dimensional array containing multiple objects, we need to loop the array out and convert the object to an array to output

<?php
namespace App\index\controller;
Use Think\controller;
Use App\index\model\admin;

Class Index extends Controller
{
    /**
     * @param string $name
    /Public Function index ($name = ' name ') c9/>{
       $admin = admin::get (1);
       Finding out the Pwn_admin_message table associated with aid 1 is all data
       $admin = $admin->adminmessage ()->select ();
        For ($i =0 $i <count ($admin); $i + +) {
            var_dump ($admin [$i]->toarray ());}}
? >

Output results:

There are two functions also by the way, one is haswhere there is a has these two are based on the relevant conditions to query, popular point is based on the Pwd_admin table, the pwn_admin_message of the conditions to query. If you change to use the field in Pwd_admin as a condition query, it will be an error.

<?php
namespace App\index\controller;
Use Think\controller;
Use App\index\model\admin;

Class Index extends Controller
{
    /**
     * @param string $name
    /Public Function index ($name = ' name ') c9/>{
     //  $admin = admin::get (1);
     $list = Admin::haswhere (' adminmessage ', [' aid ' =>1])->select ();
     $list 1=admin::has (' adminmessage ', [' aid ' =>2])->select ();
    Var_dump ($list 1[0]->toarray ());
    }

   ? >

The result of this association is normal:

If you press the Pwd_admin table field as a search condition, you will get an error. For example, I use a pwn_admin_message No field, use the user field as a condition query to try.

<?php
namespace App\index\controller;
Use Think\controller;
Use App\index\model\admin;

Class Index extends Controller
{
    /**
     * @param string $name
    /Public Function index ($name = ' name ') c9/>{
     //  $admin = admin::get (1);
    $list = Admin::haswhere (' adminmessage ', [' aid ' =>1])->select ();
     $list 1=admin::has (' adminmessage ', [' User ' => ' jiehechen123 '])->select ();
     Var_dump ($list 1[0]->toarray ());
    }
  ? >

It is good to quote the following error:

Well, I'm here to talk about so much, this article mainly talk about one-on-one and a couple of several commonly used methods of use, others have many methods of use can refer to the manual. I've tried my best to speak very carefully. If there is any understanding or have any valuable comments of the welcome message.

Want to learn more about the link model one-to-one one-to-many please click here

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.