Laravel 里,这些都是构建数据库查询时常用的条件构造方式

由 Jefsky 发布于 2025-04-01

在 Laravel 里,这些都是构建数据库查询时常用的条件构造方式,下面为你详细解释:

1. $where = []

此为创建一个空数组,在后续代码里可往该数组添加查询条件,最后再把这个数组传递给查询构建器。

$where = [];
if ($someCondition) {
    $where[] = ['column', '=', 'value'];
}
$results = DB::table('table_name')->where($where)->get();

2. ->where()

这是 Laravel 查询构建器里的一个方法,可用于添加单个查询条件。它有多种使用方式:

基本用法

$results = DB::table('table_name')
    ->where('column', '=', 'value')
    ->get();

这里的 = 是比较运算符,也能使用其他运算符,例如 ><!= 等。

省略比较运算符

$results = DB::table('table_name')
    ->where('column', 'value')
    ->get();

当省略比较运算符时,默认使用 =

多个条件

$results = DB::table('table_name')
    ->where('column1', 'value1')
    ->where('column2', 'value2')
    ->get();

多个 where 方法之间是 AND 关系。

3. ->where([])

该方法用于一次性传递多个查询条件数组。

$conditions = [
    ['column1', '=', 'value1'],
    ['column2', '>', 'value2']
];
$results = DB::table('table_name')->where($conditions)->get();

4. $where['key'] = value

这种方式是往 $where 数组添加一个关联元素。通常用于动态构建条件数组。

$where = [];
$where['column'] = 'value';
$results = DB::table('table_name')->where($where)->get();

这种方式等价于:

$results = DB::table('table_name')
    ->where('column', '=', 'value')
    ->get();

5. $where[] = ['key', '<>', 'value']

这是往 $where 数组添加一个条件子数组。<> 是不等于的比较运算符。

$where = [];
$where[] = ['column', '<>', 'value'];
$results = DB::table('table_name')->where($where)->get();

上述代码等同于:

$results = DB::table('table_name')
    ->where('column', '<>', 'value')
    ->get();

综上所述,这些方式都能用来构建数据库查询条件,可以依据具体需求选择合适的方式。

著作权归作者所有。
商业转载请联系作者获得授权,非商业转载请注明出处。
作者:JefskyWong ——程序猿甜品店
链接:https://www.jefsky.com/blog/349
来源:https://www.jefsky.com/