thinkphp hasOne与belongsTo

has_one(或has_many):外键在子关联对象中

belongs_to:外键在父联对象中

  1. 有两张表:user & userAddress

user 表字段有 id name

userAddress 表字段有 id user_id city

在user模型中关联userAddress模型时,外键在userAddress模型中应当使用 hasOne

在userAddress 模型中关联user模型时,外键在当前的userAddress模型中应当使用 belongsTo

  1. 比如有user(用户表)和login(登录日志表)两张表,一对一的关系,表设计大概如下:
表名
user表 id name
login表 id ip userid

login表有user表的外键字段userid,user表所对应的模型,就应该使用hasOne去关联login表,login表就是从属于user表;
反之,login表所对应的模型,则用belongsTo去关联user表 ,user为主,里面有一个login。

ps:hasOne和belongsTo可以同时使用,也可以单独只使用一个。

模型属性绑定与重命名

  1. belongsTo
public function addr(){
	 		 return $this->belongsTo("Address","aid","id")->bind(['zone','truename'=>'name', 'address', 'tel']);
	 }
  1. hasOne
public function profile() { 
		    return $this->hasOne(Profile::class, 'uid')->bind([ 'email', 'truename' => 'nickname', ]); 
	 }

区别:字段别名=> 数据字段名
& 数据表字段名=> 别名

关联模型修改

  1. UserLevel 模型
public function profit() { 
		return $this->hasOne('RuleProfit', 'ul_id', 'id')->bind([ 'trade_type', 'rp_status' => 'status', 'tax_point' , 'profit_rate', 'pid']); 
		 
	}
  1. UserLevelController 控制器文件
$model  = $this->demoModel->where(['id'=>$demoId])->find();
$model->profit->tax_point = $param['tax_point'];
$model->profit->profit_rate = $param['profit_rate'];

$this->demoModel 是UserLevel模型;
$model->profit 模型关联方法
$model->profit->tax_point 要修改的属性

public function ainfo(){
return $this->hasOne("Account","id","uid")->bind(['name','phone']);
//hasOne("关联表模型","关联表主键","本模型关联Account使用的外键")->bind(['关联模型Account的字段1','关联模型Account的字段2'])
}

两种写法

public function uinfo() {
		return $this->belongsTo("Users","uid","id")->bind(['name']);
		
	}
	public function ainfo() {
		return $this->hasOne(Users::class, 'id', 'uid')->bind(['name']); 
	}

本文作者:子岚天羽卿怜水

本文链接:https://www.cnblogs.com/jigr/p/15921540.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   子岚天羽卿怜水  阅读(905)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
🔑
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.