序言
thinkphp8 关联模型包含
一对一关联模型
hasOne(‘关联模型类名’, ‘外键’, ‘主键’);
一对多关联模型
hasMany(‘关联模型’,‘外键’,‘主键’);
多对多关联模型
belongsToMany(‘关联模型’,‘中间表’,‘外键’,‘关联键’);
多态关联
morphMany(‘关联模型’,‘多态字段’,‘多态类型’);
远程一对多
hasManyThrough(‘关联模型’, ‘中间模型’, ‘外键’, ‘中间表关联键’,‘当前模型主键’,‘中间模型主键’);
一对一关联模型
hasOne(‘关联模型类名’, ‘外键’, ‘主键’);
什么是一对一关联? 假设我我们有如下数据关系表
admin 表:
id:主键id
username:账号
password:密码
auth:
user_id:admin 表id
title:权限名称
rule_id:权限id
我们有一张 admin 管理表 和 权限表 我们要查询当前用户的权限信息
创建一个 admin/controller 控制器
php think make:controller admin@System/Admin
普通查询
<?php
declare (strict_types = 1);
namespace app\admin\controller\System;
use think\Request;
use app\admin\model\Admin;
class AdminController
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function getAdmin()
{
$Admin = new Admin;
$result = $Admin->where('username' , 'admin')->findOrEmpty();
if($result->isEmpty())
{
echo "No admin found";
die;
}
dump($result);
die;
}
}
模型层
管理员表 php think make:model admin@Admin
权限表 php think make:model admin@AdminAuth
<?php
declare (strict_types = 1);
namespace app\admin\model;
use think\Model;
/**
* @mixin \think\Model
*/
class Admin extends Model
{
public function auth(){
return $this->hasOne(AdminAuth::class,'user_id','id');
}
}
使用一对一查询
<?php
declare (strict_types = 1);
namespace app\admin\controller\System;
use think\Request;
use app\admin\model\Admin;
class AdminController
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function getAdmin()
{
$Admin = new Admin;
$result = $Admin->where('username' , 'admin')->findOrEmpty();
if($result->isEmpty())
{
echo "No admin found";
die;
}
dump($result->auth);
die;
}
}
<?php
declare (strict_types = 1);
namespace app\admin\controller\System;
use think\Request;
use app\admin\model\Admin;
class AdminController
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function getAdmin()
{
$Admin = new Admin;
$result = $Admin->with(['auth'])->where('username' , 'admin')->findOrEmpty();
if($result->isEmpty())
{
echo "No admin found";
die;
}
dump($result->toArray());
}
}
总结
当我们需要进行查询admin 表时查询一下管理员的权限auth时 并且auth表中只有一条关于admin表的user_id时可以使用一对一查询