解读‘一对一’对应关系

解读一对一 hasOnebelongsTo

  • 一对一怎么定义

一对一的关系要定义在 主动调用的调用方
例如:本项目中 themeimage 两个模型是一对一关系,实际业务中,我们需要从 theme模型去调用 image 模型中的图片,
所以定义模型关系需要定义在 theme 中:

theme.php
 /**     
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo     
*/   
 public function topicImage()    {        
  return $this->belongsTo('App\Models\Images', 'topic_img_id', 'id');    
}
  • hasOnebelongsTo 的区别:

hasOnebelongsTo 是有主从的或者说不能互换的;
为撒?

在设计表结构时,两个有一对一关系的模型中,一个表中会设计外键,而另一表中不会设计外键,需要用 hasOnebelognsTo 来区分
本项目中 theme 表中有 topic_img_id 对应 image 表中的 id; 而 image 表中没有定义外键,类似于 theme_id 的字段;
从这点来说,这一对一的关系是不能互换,不对等的;

<figure style="font-size: inherit; color: inherit; line-height: inherit; margin: 0px; padding: 0px;">
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');    
}
  • 总结:
  1. 一对一关系中,一对一的关系模型定义在 调用的主动方 模型中,上述中的 theme 模型;
  2. 一对一关系中,在有外键的模型中 使用 belongsTo ; 没有外键的模型 使用 hasOne;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容