gpt4 book ai didi

php - 使用 Eloquent 从带有外键的单个表中获取数据到另外两个表 - laravel

转载 作者:行者123 更新时间:2023-11-30 23:44:09 25 4
gpt4 key购买 nike

请给我三个模型:讲师、级别、类(class)。

讲师表

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

级别表

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

类(class)表

| 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 从级别模型中获取每门类(class)的讲师详细信息。任何帮助将不胜感激。提前致谢。

最佳答案

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

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

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

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

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

关于php - 使用 Eloquent 从带有外键的单个表中获取数据到另外两个表 - laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51623769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com