【问题标题】:Laravel Eloquent thee tables relationship queryLaravel Eloquent 表关系查询
【发布时间】:2021-09-25 13:19:36
【问题描述】:

我有三个mysql表:

  • 学生(受限于USER_ID
  • student_in_tournament(受限于STUDENT_IDTOURNAMENT_ID
  • 锦标赛

我需要一个雄辩的查询,通过指定的USER_ID 获取所有 学生,如果这些学生在 student_in_tournament 表中,它需要加入 锦标赛表。

如果这些学生没有参加student_in_tournament,他们不需要参加。

最后,我需要来自特定 USER_IDALL 个学生,如果他存在于 student_in_tournament 表中,则加入锦标赛...

我尝试了内部联接,但它并没有给我所有的学生,只有那些在 student_in_tournament 表中的学生。我也试过Student::with('studentInTournament.tournaments'),但它在锦标赛中给了我'null'

谢谢

【问题讨论】:

  • 首先,这不是“我需要这个,为我做”,向我们展示你的尝试...学习How to Ask...另外,请参阅文档,Laravel有一个漂亮的文档,并在那里解释...阅读它...Relations 文档...
  • 我尝试了内部连接,但它并没有给我所有的学生,只有那些在 student_in_tournament 表中的学生。我也试过 Student::with('studentInTournament.tournaments') 但它在比赛中给了我“空”
  • 再一次,阅读文档,一切都在那里解释,非常简单。

标签: php mysql sql laravel eloquent


【解决方案1】:

尝试在您的 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

【讨论】:

    猜你喜欢
    • 2013-10-03
    • 2017-07-19
    • 2015-01-21
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2015-12-22
    相关资源
    最近更新 更多