解读一对一 hasOne
和 belongsTo
- 一对一怎么定义
一对一的关系要定义在
主动调用的调用方
例如:本项目中theme
和image
两个模型是一对一关系,实际业务中,我们需要从theme
模型去调用image
模型中的图片,
所以定义模型关系需要定义在theme
中:
theme.php
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function topicImage() {
return $this->belongsTo('App\Models\Images', 'topic_img_id', 'id');
}
-
hasOne
和belongsTo
的区别:
hasOne
和belongsTo
是有主从的或者说不能互换的;
为撒?在设计表结构时,两个有一对一关系的模型中,一个表中会设计外键,而另一表中不会设计外键,需要用
<figure style="font-size: inherit; color: inherit; line-height: inherit; margin: 0px; padding: 0px;">hasOne
和belognsTo
来区分
本项目中theme
表中有topic_img_id
对应image
表中的id
; 而image
表中没有定义外键,类似于theme_id
的字段;
从这点来说,这一对一的关系是不能互换,不对等的;theme表
image.png
在有外键的模型 theme
中, 使用 belongsTo
theme.php
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function topicImage() {
return $this->belongsTo('App\Models\Images', 'topic_img_id', 'id');
}
- 总结:
- 一对一关系中,一对一的关系模型定义在
调用的主动方
模型中,上述中的theme
模型; - 一对一关系中,在有外键的模型中 使用
belongsTo
; 没有外键的模型 使用hasOne
;