一对多关联模型
hasMany(‘关联模型’,‘外键’,‘主键’);
管理员表
CREATE TABLE `turing_admin` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` char(32) DEFAULT NULL COMMENT '账号',
`password` char(32) DEFAULT NULL COMMENT '密码',
`status` tinyint(1) DEFAULT NULL COMMENT '1 启用 0 禁用',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;
角色表
CREATE TABLE `turing_admin_auth` (
`user_id` bigint(20) NOT NULL COMMENT '管理员id',
`title` char(32) DEFAULT NULL COMMENT '权限名称'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
创建控制器
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->with(['auth'])->where('username' , 'admin')->findOrEmpty();
if($result->isEmpty())
{
echo "No admin found";
die;
}
dump($result->toArray());
}
}
创建模型
管理员表 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->hasMany(AdminAuth::class,'user_id','id');
}
}