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 files
The next step is to create a new model class file corresponding to the two data tables. 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('Associated model name','Foreign key name',' Primary key name',['Model alias definition'],'join type');
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 there must be at least one 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 obtains The corresponding will be automatically converted when the user_profile association attribute is read, the corresponding association 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, if I defined the associated method in the admin model above, you need to introduce the admin model. 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()); } ?>
Running result:
If your result is like this, only the admin administrator table data, 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, I don’t use numeric numbers for convenience. 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
The use of one-to-many association and one-to-one association are 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 parameters are:
hasMany('Associated model name', 'Foreign key name', 'Primary key name', ['Model alias definition']);
Still take 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:
有几个管理员没有数据,不过没关系足够测试就可以了。好了废话不多说,开始进入正题。
相信大家一看就知道下面这个是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()); } } ?>
就会报出如下错误:
推荐教程:thinkphp教程
The above is the detailed content of The definition and use of association models in thinkphp5. For more information, please follow other related articles on the PHP Chinese website!