如何包装 Laravel eloquent 条件以创建以下查询

How do I wrap Laravel eloquent conditions to create the following query

我有一个简单的结果 table 如下所示 -

id, home_team_id, away_team_id, home_score, away_score, media
1       511          322            4           0       'a4vw'
2       232          511            2           2       'bf34',
3       111          511            2           3        NULL        

我能够获取 'team_id' 值为 home_team_idaway_team_id = 511 的所有行,但我还需要检查以确保media 列是 NOT NULL 原始 SQL 查询会像这样

SELECT * FROM results where (home_team_id = 310718 OR away_team_id = 310718) and media is not null;

但是我正在尝试尽可能多地使用 Laravel Eloquent 方法,因为我正在学习这个所以可以使用如下一种方法(效果很好)但是我尝试在我的方法中不使用任何 DB::raw 方法

DB::table("results")
->where(DB::raw("(home_team_id = 511 or away_team_id = 511)"))
->whereNotNull("media")
->get();

我将如何修改我的结果模型中的以下内容以执行与上述查询相同的查询returns所有结果我只期望 2 个结果,因为媒体列有一个 NULL 条目

return Result::where('home_team_id', '=', $clubId)
             ->orWhere('away_team_id', '=', $clubId)
             ->whereNotNull('media')
             ->get();

您查询中的问题是在错误的位置使用了 orWhere 条件。由于您的查询中有两个主要条件,一个是

'team_id' value is either the home_team_id OR away_team_id

而第二个条件是

media column is NOT NULL

因此您必须将两个条件分解为两个单独的条件语句。

尝试以下查询

return Result::where(function($query) use ($clubId) {
   $query->where('home_team_id', '=', $clubId)
         ->orWhere('away_team_id', '=', $clubId);
})
->whereNotNull('media')
->get();

你能试试这个吗?

return Result::where(function($query) use ($clubId) {
            $query->where('home_team_id', $clubId)
                ->orWhere('away_team_id', $clubId);
        })->whereNotNull('media')->get();

初学者常犯的错误

You should always group orWhere calls in order to avoid unexpected behavior when global scopes are applied.

https://laravel.com/docs/8.x/queries#logical-grouping