代码之家  ›  专栏  ›  技术社区  ›  Mathieu Mourareau

带查询的数据库设计雄辩题

  •  0
  • Mathieu Mourareau  · 技术社区  · 6 年前

    我需要创建一个应用程序谁管理足球表

    实际上我有一张桌子,用来存放两队的比赛

    match :
    -id
    -dt_math
    -club_home_id
    -club_visitor_id
    

    每个队都有一张表来创建球员名单。

    因此,我创建了表match\ sheet来存储来自团队的两张表。

    match_sheet :
    -id
    -match_id
    

    为了在每张表中存储玩家,我创建了表match\u sheet\u player

    match_sheet_player:
    -id
    -match_sheet_id
    -player_id
    

    现在我只需要显示在我的视图中有两个表的匹配。我不知道怎么做到。

    我提出的第一个问题是:

      $matchs_sheets = MatchSheet::all();
    
        $matchs = Match::whereIn('id', $matchs_sheets->pluck('match_id'))->orderByDesc('dt_match')->paginate(5);
    

    但即使有一张纸,但不是两张都有,这也会让我赢。如果有两张床单的话,我真的需要把火柴拿出来。

    更新:

    有两张1659的唱片。1659是比赛的id。所以我只想展示1659场比赛,而不是1649场,因为这场比赛只有一个记录 enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   Joel Hinz    6 年前

    假设模型关系设置正确,则仅当相关模型的计数至少为2时,才可以使用 has() . 例如:

    $matches = Match::whereIn('id', $ids)->has('matchSheet', '=', 2)...
    

    你的关系应该这样建立,例如:

    // on Match model
    public function matchSheets()
    {
        return $this->hasMany(MatchSheet::class);
    }
    
    // on MatchSheet model
    public function match()
    {
        return $this->belongsTo(Match::class);
    }
    

    此处文档: https://laravel.com/docs/5.6/eloquent-relationships#one-to-many -我真的建议你通读它们,它们最终会为你节省大量的时间!