【问题标题】:How to join three table by laravel eloquent model Laravel 5如何通过 laravel eloquent 模型 Laravel 5 加入三个表
【发布时间】:2016-01-20 17:22:53
【问题描述】:

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

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

$data['lessons']->student

我想得到什么:

ID |日期 |用户名 |老师的名字

我的代码:

我有 3 张桌子:

  • 课程{id、日期、fk_students_id、fk_teachers_id}
  • 学生 {id, firstname}
  • 老师{id, firstname}

模型Lesson.php

public function student(){

    return $this->belongsTo('App\Student');
}

public  function teacher(){

    return $this->belongsTo('App\Teacher');
}

模型Student.php

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

模型Teacher.php

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

控制器中

$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
}
]

感谢您的帮助!

【问题讨论】:

  • 删除return var_dump($data['lessons']->student);并放入dd($data);,请发布结果
  • @AndreL 我已经更新了帖子。感谢您的帮助。

标签: php laravel eloquent laravel-5.1


【解决方案1】:

如你所见,

#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');
}

【讨论】:

  • Laravel 能知道fk_students_id 是外键吗? laravel 知道这种模式吗?我总是声明local_key's 和parent_key's。只是问@Rudie。
猜你喜欢
  • 2015-05-23
  • 2016-04-03
  • 1970-01-01
  • 1970-01-01
  • 2019-10-04
  • 2019-06-02
  • 2015-03-12
  • 2016-07-13
  • 2017-09-13
相关资源
最近更新 更多