hasone 一对一 正向关联:在主表模型中写与副表的关联方法
表结构
user_basic 副表
uid,name,city,idcard
user 主表
uid,name,lastLogintime
UserModel
//foreignKey 外键 指的是 UserBasic 表与user表对应的数据
//localKey 主键 指的是 当前User表的主键
namespace app\model;
use think\Model;
use app\model\Order as OrderModel;
class User extends Model
{
public function UserBasic(): \think\model\relation\HasOne
{
//foreignKey 外键 指的是 UserBasic 表与user表对应的数据
//localKey 主键 指的是 当前User表的主键
return $this->hasOne(UserBasic::class,'uid','uid');
}
}
UserController
<?php
declare (strict_types = 1);
namespace app\api\controller;
use app\model\User as UserModel;
class User extends Base
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
// 获取数据列表
$data = UserModel::where('uid',"91")->find();
return json($data->user_basic);
}
}
}
belongsTo 反向关联:在副表模型中写与主表的关联方法
UserBasicModel
namespace app\model;
use think\Model;
use app\model\User;
class UserBasic extends Model
{
/**
* @return \think\db\BaseQuery|\think\model\relation\HasMany
*/
protected $name = 'user_basic';
public function Users(): \think\model\relation\BelongsTo
{
return $this->belongsTo(User::class,'uid','uid');
}
}
UserController
namespace app\api\controller;
use \app\model\UserBasic as UserBasicModel;
class UserBasic extends Base
{
public function index(): \think\response\Json
{
$user_basic = UserBasicModel::where('uid',91)->find();
return json($user_basic->Users);
}
}
标签:uid,一对一,app,关联,tp5,user,UserBasic,model,think
From: https://www.cnblogs.com/w-m-y/p/16909754.html