一对多关系很多工作-Laravel

时间:2018-09-21 07:20:42

标签: php laravel

试图使用一对多关系显示与雇主相关的所有工作,但我遇到此错误。

LogicException in Model.php line 2723:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

我的代码: 雇主模式 雇主类扩展模型

{
    public function jobs(){
        $this->hasMany('App\Job','employer_id');
    }
}

路线:

Route::get('/find_job',function(){
    $employer=Employer::find(1);
    foreach($employer->jobs as $job){
        echo $job->created_at."<br>";
    }
});

2 个答案:

答案 0 :(得分:1)

在您的雇主模型中,只需返回

public function jobs()
  {
      return $this->hasMany('App\Job','employer_id');
  }

在您的工作模型中,返回类似的雇主

public function employer()
  {
      return $this->belongsTo('App\Employer');
  }

答案 1 :(得分:0)

您必须返回关系:

<form id = "myForm"  action = "">
  <p>
    <label> <input type = "radio" name = "myChoice" value = "A" /> 
    A </label>
    <br />
    <label> <input type = "radio"  name = "myChoice" value = "B" />
    B </label>
    <br />
    <label> <input type = "radio"  name = "myChoice" value = "C"/> 
    C </label></form>