laravel查询写多个条件

在Laravel中,我们经常需要根据多个条件进行查询。这些条件可能包括字段值、时间范围、关系等等。在本文中,我们将讨论如何使用Laravel Eloquent进行多条件查询。

  • 基本查询
  • 在Laravel中进行查询时,我们可以使用基本的查询方法,例如whereorWherewhereInwhereNotIn等。这些查询方法可以通过链式调用来组合多个查询条件。例如,我们可以使用以下代码来查询文章表中ID为1且状态为1的文章:

    $article = DB::table('articles') ->where('id', 1) ->where('status', 1) ->first();登录后复制

  • 高级查询
  • Laravel中的Eloquent模型还提供了许多高级查询方法来处理更复杂的查询。以下是一些常用的高级查询方法:

    2.1 whereBetween方法

    whereBetween方法允许我们查询在指定范围内的记录。例如,我们可以使用以下代码来查询创建时间在2019年到2020年之间的文章:

    $articles = DB::table('articles') ->whereBetween('created_at', ['2019-01-01', '2020-12-31']) ->get();登录后复制

    orWhere方法允许我们查询多个条件中的任意一个条件满足即可。例如,我们可以使用以下代码来查询状态为1或2的文章:

    $articles = DB::table('articles') ->where('category_id', 1) ->orWhere('status', 1) ->get();登录后复制

    whereHas方法允许我们查询关联模型中满足筛选条件的记录。例如,我们可以使用以下代码来查询所有有评论的文章:

    $articles = DB::table('articles') ->whereHas('comments') ->get();登录后复制

    $articles = DB::table('articles') ->whereHas('comments', function($query) { $query->where('status', 1); }) ->get();登录后复制

    2.4 whereInwhereNotIn方法

    whereInwhereNotIn允许我们按照指定字段的取值范围筛选结果。例如,我们可以使用以下代码来查询文章状态为1、2、3的记录:

    $articles = DB::table('articles') ->whereIn('status', [1, 2, 3]) ->get();登录后复制