has_one(或has_many):外鍵在子關聯對象中
belongs_to:外鍵在父聯對象中
- 有兩張表:user & userAddress
user 表字段有 id name
userAddress 表字段有 id user_id city
在user模型中關聯userAddress模型時,外鍵在userAddress模型中應當使用 hasOne
在userAddress 模型中關聯user模型時,外鍵在當前的userAddress模型中應當使用 belongsTo
- 比如有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可以同時使用,也可以單獨只使用一個。
模型屬性綁定與重命名
- belongsTo
public function addr(){
return $this->belongsTo("Address","aid","id")->bind(['zone','truename'=>'name', 'address', 'tel']);
}
- hasOne
public function profile() {
return $this->hasOne(Profile::class, 'uid')->bind([ 'email', 'truename' => 'nickname', ]);
}
區別:字段別名=> 數據字段名
& 數據表字段名=> 別名
關聯模型修改
- UserLevel 模型
public function profit() {
return $this->hasOne('RuleProfit', 'ul_id', 'id')->bind([ 'trade_type', 'rp_status' => 'status', 'tax_point' , 'profit_rate', 'pid']);
}
- 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']);
}