【问题标题】:How to check if related table doesn't have record如何检查相关表是否没有记录
【发布时间】:2021-01-28 13:54:15
【问题描述】:

matches 表与 score 表有关系。

我需要在分数表中获取所有没有记录的匹配项。

尝试过,但没有成功:

$upcomingMatch = Match::join('scores', 'matches.id', '=', 'scores.match_id')
           ->where('away_team_id', '=', '1')
           ->orWhere('home_team_id', '=', '1')
           ->where('scores.match_id', null)
           ->latest('matches.match_date')
           ->first();

【问题讨论】:

  • 他们之间有建立关系吗?如果是这样,请检查 doesntHave 方法
  • 我非常同意@lagbox,如果您设置了关系,那么 doesnsHave 是这里标准且简单的解决方案。 laravel.com/docs/8.x/…

标签: php laravel model-view-controller laravel-query-builder


【解决方案1】:

如果您使用关系,则可以使用 doesntHave() ,但是如果您在问题中使用查询生成器,则可以使用这些代码,我看到您的 where 条件需要一些调整才能使用嵌套条件。如果要检索空记录,则在scores 表中使用whereNull,这不是与matches 表的关系键,在此示例中我使用scores.id

获取分数为空的matches(使用leftJoin 和一些附加条件)

$upcomingMatch = Match::leftjoin('scores', 'matches.id', '=', 'scores.match_id')
           ->where(function ($where)
           {
               $where->where('matches.away_team_id', '=', '1')
               ->orWhere('matches.home_team_id', '=', '1');
           })
           ->whereNull('scores.id')
           ->latest('matches.match_date')
           ->first();

【讨论】:

    【解决方案2】:

    试试:

    $upcomingMatch = Match::join('scores', 'matches.id', '=', 'scores.match_id')
               ->where('away_team_id', '=', '1')
               ->orWhere('home_team_id', '=', '1')
               ->whereNull('scores.match_id')
               ->latest('matches.match_date')
               ->first();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 2018-11-25
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      相关资源
      最近更新 更多