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']); 
	}
posted @ 2022-02-22 10:10  子岚天羽卿怜水  阅读(827)  评论(0编辑  收藏  举报