如何通过laravel雄辩模型连接三个表


How to join three table by laravel eloquent model Laravel 5

我在网上搜索了我的问题,但我找不到答案。我找到了一个关于StackOverflow的教程,但对于我的例子来说,它不起作用。

当我运行以下代码时,它返回NULL:

$data['lessons']->student

我想要得到什么:

ID |日期|用户。firstname | Teacher.firstname

我代码:

我有3个表:

  • 课程{id,日期,fk_students_id, fk_teachers_id}
  • student {id, firstname}
  • 老师{id, firstname}
<

模型em> Lesson.php :

public function student(){
    return $this->belongsTo('App'Student');
}
public  function teacher(){
    return $this->belongsTo('App'Teacher');
}
<

模型em> Student.php :

public function lessons(){
    return $this->hasMany('App'Lesson', 'fk_students_id');
}
<

模型em> Teacher.php :

public function lessons(){
    return $this->hasMany('App'Lesson', 'fk_teachers_id');
}

Controller:

$data['lessons'] = Lesson::with(['student', 'teacher'])->first();
return var_dump($data['lessons']->student);

dd($data);输出:

array:1 [
"lessons" => Lesson {#303 
#connection: null
#table: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:10 [
  "id" => 1
  "date" => "2015-07-25"
  "start" => "12:30:00"
  "end" => "13:00:00"
  "fk_students_id" => 1
  "fk_teachers_id" => 1
  "lesson_array" => "[{"id":"1", "result":"0"},{"id":"2", "result":"1"},{"id":"15", "result":"2"}]"
  "slug" => "562153eae355e"
  "created_at" => "0000-00-00 00:00:00"
  "updated_at" => "0000-00-00 00:00:00"
]
#original: array:10 [
  "id" => 1
  "date" => "2015-07-25"
  "start" => "12:30:00"
  "end" => "13:00:00"
  "fk_students_id" => 1
  "fk_teachers_id" => 1
  "lesson_array" => "[{"id":"1", "result":"0"},{"id":"2", "result":"1"},{"id":"15", "result":"2"}]"
  "slug" => "562153eae355e"
  "created_at" => "0000-00-00 00:00:00"
  "updated_at" => "0000-00-00 00:00:00"
]
#relations: array:2 [
  "student" => null
  "teacher" => null
]
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [
  0 => "*"
]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
]

谢谢你的帮助!

如你所见,

#relations: array:2 [
  "student" => null
  "teacher" => null
] 

都是空的,这是因为外键的名字。

所以你应该在模型上设置它们:

public function student(){
    return $this->belongsTo('App'Student', 'fk_teachers_id', 'id');
}
public  function teacher(){
    return $this->belongsTo('App'Teacher', 'fk_students_id','id');
}