解读‘一对一’对应关系

2018-06-30  本文已影响9人  Monkey_zhou

解读一对一 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 是有主从的或者说不能互换的;
为撒?

在设计表结构时,两个有一对一关系的模型中,一个表中会设计外键,而另一表中不会设计外键,需要用 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;
上一篇 下一篇

猜你喜欢

热点阅读