【问题标题】:How to make Eloquent Relationships for one to one relationship like this如何为这样的一对一关系建立雄辩的关系
【发布时间】:2018-12-24 10:08:47
【问题描述】:

我的表结构是这样的:

farmers
    id
    name
    education_id (used to capture max education)

educations (names of the education levels like BS / MS / PhD etc.)
    id
    name

我尝试了以下代码但失败 -

In farmers model (app/fermers.php) I added this code:

public function education()
{
    return $this->hasOne(Educations::class);
}

如何建立关系?

【问题讨论】:

  • "失败" 什么失败? "Educations::class" 你的模型叫Educations?你use App\Educations; 在文件顶部吗?
  • 在您的情况下,您必须使用belongsTo 而不是hasOne Cause of Educatoin Farmers table education_id belongsTo Education Table

标签: php laravel orm eloquent


【解决方案1】:

在你的情况下教育有很多农民,农民属于教育。

你应该使用belongsTo():

public function education()
{
    return $this->belongsTo(Educations::class);
}

【讨论】:

    【解决方案2】:

    这条线应该是,

     return $this->hasOne('App\yourModel');
    

    例如,

     return $this->hasOne('App\Educations');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2012-10-08
      • 2022-06-11
      • 2019-05-07
      • 2020-09-20
      • 2018-11-14
      • 2015-07-01
      相关资源
      最近更新 更多