簡體   English   中英

Laravel連接2個表,第一個表一個數據,第二個表多個數據

[英]Laravel Join 2 tables , one data from first table and multiple row from second table

FirstTable

id | 名稱|


1 | 學生1 |

2 | 學生2 |

3 | 學生3 |

4 | 學生4 |

==============================

SecondTable

ID | stud_id | 主題| 標記


1 | 1 | 數學| 50

2 | 1 | 英語| 45

3 | 2 | 數學| 20

4 | 3 | 數學| 40

我將如何使用上面的表結構在laravel中查詢..我需要outpus作為

{

    "id": 1,

    "name":"student1"

    "marks":[

        {

            "subject":"maths",

            "marks":50,

        },

        {

            "subject":"emglish",

            "marks":45,

        }

    ]

}

我已經在Laravel查詢生成器中做到了。 請看下面。

$stud = DB::table('FirstTable')
               ->join('SecondTable','FirstTable.id','=','SecondTable.stud_id')
               ->where('FirstTable.id','=','1')
               ->get();
dd($stud);

我正在以雄辯的方式做這件事。 在學生模型中創建關系方法。 這是一個學生可以有很多學科關系

public function subject(){
return $this->hasMany('App\"the second table model name",'stud_id');

}

那么您在控制器中可以像訪問它一樣

public function index(){
$student = Student::find("Student_id")->subject;
dd($student);
}

請閱讀文檔以更好地了解https://laravel.com/docs/5.5/eloquent-relationships

您可以使用這些表創建關系。 在這里,您需要一對多的關系。

您需要學生,課程表

學生們

Schema::create('students', function (Blueprint $table) {
$table->increments('id');
$table->string('student_name')
});

教訓

Schema::create('lessons', function (Blueprint $table) {
$table->increments('id');
$table->integer('student_id');
$table->integer('exam_number'); // there will be many exams right ?
$table->integer('lesson1')
$table->integer('lesson2');
$table->integer('lesson-etc');
$table->timestamps();

$table->foreign('student_id')->references('id')->on('students')
});

然后如下編輯模型

學生模型;

public function lessons(){

       return $this->hasMany('App\Lesson','student_id','id');
    }

並在您的課程模型中;

 public function students(){

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

然后在您的控制器中

$students = Student::whereHas('lessons', function ($query) {

            $query->where("exam_number", 2 (or which exam));
        })->get();

最后,在您的刀片中;

 <table >
  <tr>
    <th>Student Name</th>
    <th>Lesson 1</th>
    <th>Lesson 2</th>
  </tr>
@foreach($students as $student)
  <tr>
    <td>{{$student->student_name}}</td>
    <td>{{$student->lessons->lesson1}}</td>
    <td>{{$student->lessons->lesson2}}</td>
  </tr>
@endforeach
</table> 

這應該是工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM