【问题标题】:Using Eloquent to fetch data from a single table with foreign keys to two other tables - laravel使用 Eloquent 从具有外键的单个表中获取数据到另外两个表 - laravel
【发布时间】:2018-08-01 00:26:33
【问题描述】:

请给我三个模型:讲师、级别、课程。

讲师表

| ID | Name_of_lecturer  
+----+----------------  
| 1 .| Prof John Doe  
+----+----------------  
| 2 .| Prof Jane Doe

等级表

| ID | Name 
+----+----------------  
| 1 .| Level 1  
+----+----------------  
| 2 .| Level 2

课程表

| ID | level_id | lecturer_id | course_info
+----+----------+-------------+----------------------------------  
| 1  | 2        | 3             a topic in level 2 by lecturer 3
+----+----------+-------------+----------------------------------
| 2  | 5        | 6           | a topic in level 5 by lecturer 6

我真的很困惑如何使用 Eloquent 从 Levels 模型中获取每门课程的讲师详细信息。任何帮助将不胜感激。提前致谢。

【问题讨论】:

  • 你能在问题的最后加上你的预期结果吗?
  • 我阅读了文档并遇到了各种错误。我希望能够从级别模型中访问它,在那里我可以获得所有课程及其各自的讲师。谢谢。
  • LecturerLevel 之间存在BelongsToMany 关系。看看documentation

标签: php mysql laravel eloquent


【解决方案1】:

由于一位讲师可以拥有许多课程,因此您正在寻找一对多的关系。但是由于您要从课程(很多)到讲师(一个),所以您正在寻找这个:

在您的Course 类中添加以下函数:

public function lecturer(){
    return $this->belongsTo(Lecturer::class);
}

这将允许您根据需要使用$course->lecturer()$course->lecturer->Name_of_lecturer

这里是 Laravel 文档的相关链接:Eloquent: Relationships - One to Many (Inverse)

【讨论】:

    【解决方案2】:

    如果你不是很熟悉 laravel 通过 Models 的 eloquent,你可以使用 JOIN 查询(​​内连接或任何你需要的)。 例如:

    $lecturersDetails = DB::table('course')->join('lecturers','id','=','lecturer_id')->get();
    

    【讨论】:

    • 你的回复没有使用 Eloquent
    猜你喜欢
    • 2020-10-24
    • 2018-12-08
    • 2020-12-30
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2013-05-17
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多