解读‘一对一’对应关系
2018-06-30 本文已影响9人
Monkey_zhou
解读一对一 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;