Define one-to-one association
It is assumed that you have configured the thinkphp5 environment and the database connection is OK. I want to associate two tables through the model and then get the information of the two tables by calling the controller.
Now I have prepared two tables, an administrator table pwn_admin and an administrator information table pwn_admin_message. In order to make it easier to understand, I have posted the table structures of the two tables.
The following is the table structure information of the two tables:
CREATE TABLE `pwn_admin` ( `id` int(6) NOT NULL AUTO_INCREMENT, `user` varchar(30) NOT NULL DEFAULT '', `password` varchar(50) NOT NULL DEFAULT '', `name` varchar(50) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
CREATE TABLE `pwn_admin_message` ( `id` int(6) NOT NULL AUTO_INCREMENT, `email` varchar(30) NOT NULL DEFAULT '', `mobile` varchar(50) NOT NULL DEFAULT '', `aid` int(11) NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
Building model file
The next step is to create a new model class corresponding to the two data tables document. Create a new model directory under the module and then create two new files and name them according to the corresponding tables:
Model naming
The naming rule for model classes is to remove the table The prefixed data table name is named in camel case with the first letter capitalized. For example, the table prefix of the above two tables is pwn_, which needs to be omitted in the model name. Therefore, the model class name of the pwn_admin table is Admin, and the model class name of pwn_admin_message is AdminMessage
The parameters of the hasOne method include:
hasOne(‘关联模型名’,’外键名’,’主键名’,[‘模型别名定义’],’join类型’);
The default join type is 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为外键id是adminmessage表关联admin表的外键 //id是 admin表的主键 return $this->hasOne('AdminMessage','aid','id')->field('id,coltype,auth,name,intro,xuhao,pid,pname'); } } ?>
After the Admin model defines the associated methods, there is no need to write any corresponding methods in the AdminMessage model, but it must be at least There must be an empty model corresponding to the pwn_admin_message table.
Correspondingly, if you write
<?php namespace app\index\model; use think\Model; class AdminMessage extends Model{ } ?>
in this model, one thing to note is that the naming convention for associated methods is camel case, while associated attributes are generally lowercase and underlined. The system The corresponding will be automatically converted when obtained. When reading the user_profile associated attribute, the corresponding associated method should be userProfile.
Controller call
If you want to use the associated model in the controller, you need to introduce the model class first. For example, I defined the associated method in the admin model above. You 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 是获取id为 1 的数据 //find() 是查找 //toArray() 是获取到的数据转为数组 $admin= Admin::get(1); var_dump($admin->find()->toArray()); } ?>
Now you can visit the following browser to see the results:
If your result is like this, there is only data in the admin administrator table, don’t worry this is normal. If you want to get the data of the associated table pwn_admin_message, you need to first call the AdminMessage() model method just defined, and then point to the find() method to retrieve the data.
Note:
This find() method cannot be omitted. I have not been able to retrieve the complete administrator information because I did not add this method.
<?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') { $admin= Admin::get(1); //查询出pwn_admin_message 表aid为 1 的一条数据,然后转数组。 $admin= $admin->AdminMessage->find()->toArray(); var_dump($admin); } } ?>
The result obtained is
Because it is a test, for the sake of convenience, I don’t use numeric numbers. I use text codes directly, which is more intuitive and clear.
hasWhere() method:
If you want to query the data of the current model based on the query conditions of 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') { $admin=Admin::hasWhere('AdminMessage',['email'=>'guanliB@ggg.com']); $admin=$admin->find()->toArray(); var_dump($admin); } } ?>
Output result:
Define one-to-many association
One-to-many association and one-to-one association The usage is almost the same, the difference is that the method names are different. The method name used in the model for one-to-many is hasMany. The usage methods and parameters of hasMany and hasOne are basically the same.
hasMany parameter is:
hasMany(‘关联模型名’,’外键名’,’主键名’,[‘模型别名定义’]);
Still taking the above two tables as an example, but in order to match the one-to-many association, the content of pwn_admin_message and the aid field need to be slightly modified. Change it to an administrator with multiple mobile phone numbers and multiple email addresses.
In order to facilitate understanding, I have screenshots of the data contents of the two tables.
The following picture is the content of the pwn_admin_message table:
The following picture is the content of the pwn_admin table:
There are a few administrators who don’t have data, but it doesn’t matter as long as it’s enough for testing. Okay, without further ado, let’s get to the point.
相信大家一看就知道下面这个是admin模型的内容,对应的是pwd_admin 表
<?php namespace app\index\model; use think\Model; class Admin extends Model{ public function AdminMessage(){ //pid为外键id是adminmessage表关联admin表的外键 //id是 admin表的主键 return $this->hasMany('AdminMessage','aid','id'); } }
而这下面这个是 AdminMessage 对应的是哪张表我就不说了。这和一对一关联一样也可以是个空模型
<?php namespace app\index\model; use think\Model; class AdminMessage extends Model{ /* function Admin(){ return $this->belongsTo('Admin','aid','id'); } */ } ?>
控制器调用,这回就有点不一样了。因为返回的数据是一个二维数组里面包含了多个对象所以需要把数组循环出来并把对象在转为数组才能输出
<?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') { $admin= Admin::get(1); //查找出 pwn_admin_message 表关联aid为1是所有数据 $admin= $admin->AdminMessage()->select(); for($i=0;$i<count($admin);$i++){ var_dump($admin $i]->toArray()); } } } ?>
输出结果:
还有两个函数也顺便说一下了,一个是 hasWhere 还有一个 has 这两个都是根据关联条件来查询的,通俗点讲就是根据关联到 pwd_admin 表,的 pwn_admin_message 表字段的条件来查询的。如果换过来用pwd_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') { // $admin= Admin::get(1); $list= Admin::hasWhere('AdminMessage',['aid'=>1])->select(); $list1=Admin::has('AdminMessage',['aid'=>2])->select(); var_dump($list1[0]->toArray()); } } ?>
这样子关联得出的结果是正常的:
如果按 pwd_admin 表的字段做为搜索条件就会报错。比如我用一个 pwn_admin_message 没有的字段,用user字段来做为条件查询试试。
<?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') { // $admin= Admin::get(1); // $list= Admin::hasWhere('AdminMessage',['aid'=>1])->select(); $list1=Admin::has('AdminMessage',['user'=>'jiehechen123'])->select(); var_dump($list1[0]->toArray()); } } ?>
就会报出如下错误:
推荐教程:《TP5》
The above is the detailed content of Introduction to the definition and use of thinkphp association models. For more information, please follow other related articles on the PHP Chinese website!