簡體   English   中英

Laravel Eloquent 表關系查詢

[英]Laravel Eloquent thee tables relationship query

我有三個 mysql 表:

  • 學生(受USER_ID約束)
  • student_in_tournament (受STUDENT_IDTOURNAMENT_ID約束)
  • 錦標賽

我需要一個雄辯的查詢,通過指定的USER_ID獲取所有學生,如果這些學生在student_in_tournament表中,則需要加入錦標賽表。

如果這些學生不在student_in_tournament 中,則他們不需要加入某些東西。

最后,我需要來自一個特定USER_ID所有學生,如果他存在於 student_in_tournament 表中,則參加錦標賽......

我嘗試了內部聯接,但它並沒有給我所有的學生,只有那些在student_in_tournament表中的學生。 我也試過Student::with('studentInTournament.tournaments')但它在錦標賽中給了我 'null'

謝謝

嘗試在您的StudentTournament模型之間創建 M:N 關系。 由於您的表名和列名不符合 Eloquent 的要求,因此您需要在創建關系時傳遞所有 4 個參數。

https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-model-structure

// Student model
public function tournaments()
{
    return $this->belongsToMany(Tournament::class, 'student_in_tournament', 'STUDENT_ID', 'TOURNAMENT_ID');
}

https://laravel.com/docs/8.x/eloquent-relationships#many-to-many-defining-the-inverse-of-the-relationship

// Tournament model
public function students()
{
    return $this->belongsToMany(Student::class, 'student_in_tournament', 'TOURNAMENT_ID', 'STUDENT_ID');
}
$students = Student::query()
    ->where('USER_ID', $user_id) // or whereIn('USER_ID', $user_ids) if you have multiple user ids
    ->with('tournaments')
    ->get();    

https://laravel.com/docs/8.x/blade#loops

@foreach($students as $student)
  <!-- show student information -->
  @forelse($student->tournaments as $tournament)
    <!-- show tournament information -->
  @empty
    <!-- student has no tournaments -->
  @endforelse
  <hr>
@endforeach

暫無
暫無

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

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