One-to-one association in ThinkPHP5 model

Define a one-to-one relationship. For example, a user has a personal data.
In fact, the table in the program is not directly created by Navicat or other tools at the beginning, but through the ER diagram, which reflects the relationship between a table and a graph. The relationship between a certain table comes from the establishment of the corresponding table, which is related through the foreign key.
First create a new table for user, as shown in the figure:
Insert picture description here
Fill in content:
Insert picture description here
Create a table and
Insert picture description here
fill in content for info :
Insert picture description here
Here we need to know that in the setting, we believe that each user can only have one personal information , So the relationship between the user and the info table should be a one-to-one relationship (that is, a user corresponds to a personal information), let's start the association in the model.

Create User.php and Info.php in the model:

<?php

namespace app\index\model;
use think\Model;
class User extends Model
{
    public function profile(){
        //hasOne()方法中第一个为关联的模型名称,第二个为关联的外键,
        //所以这里分别是Info模型和uid外键
        return $this->hasOne('Info','uid');
    }

    public function Memberdata(){
        $Member= new User();
        $data=$Member->with('profile')->select();
        return $data ;
    }
}

The control layer code is as follows:

<?php
namespace app\index\controller;
use app\index\model\User;
use think\Controller;
class Index extends Controller{
    
    public function index(){
        $MemberData= new User();
        $data=$MemberData->Memberdata();
        return json($data);
    }
    
}

The results are as follows:
Insert picture description here
If you only want to enter some field content, you only need to add the field() method to filter it out.

public function profile(){
        //hasOne()方法中第一个为关联的模型名称,第二个为关联的外键,
        //所以这里分别是Info模型和uid外键
        return $this->hasOne('Info','uid')->field('uid,phone,email');
}

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 in the control layer, for example:

public function index(){

        $user = User::hasWhere('profile',['email'=>'cc.com'])->find();
        echo $user->username;

    }

For more model one-to-one association methods, please see the official manual:

https://www.kancloud.cn/manual/thinkphp5/142357

Finally, due to the associated preloading in the model, when the large amount of data is large, it can load faster than the jion() method, whether it is LeftJion, RightJion or InnerJion, so I recommend that you use the model more.

Guess you like

Origin blog.csdn.net/hgb24660/article/details/100162940