Laravel Eloquent 中的链式或分组多个 WHERE 子句
在 Laravel Eloquent 查询中使用多个 WHERE 子句在使用标准链接语法。然而,有几种替代方法可以提高代码的优雅性和可读性。
使用基于数组的 WHERE 子句
在 Laravel 5.3 中引入, array-基于 WHERE 子句允许您在一次调用中对多个条件进行分组。这可以显着减少所需的代码行数,如以下示例所示:
$query->where([ ['column_1', '=', 'value_1'], ['column_2', '!=', 'value_2'], ['column_3', '=', 'value_3'], ... ]);
对 AND 操作的 WHERE 子句进行分组
如果您的所有WHERE 子句使用 AND 运算符,您可以将它们分组到一个数组中并将其传递给 where 方法。这与基于数组的方法类似,但显式指定 AND 条件。
$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...]; $results = User::where($matchThese)->get();
使用 OR 运算符组合组
使用两者创建更复杂的查询AND 和 OR 运算符,可以使用嵌套数组。以下示例结合了前面的两种技术:
$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...]; $orThose = ['yet_another_field' => 'yet_another_value', ...]; $results = User::where($matchThese) ->orWhere($orThose) ->get();
此查询将生成以下 SQL:
SELECT * FROM users WHERE (field = value AND another_field = another_value AND ...) OR (yet_another_field = yet_another_value AND ...)
通过使用这些替代方法,您可以提高查询的清晰度和简洁性雄辩的查询,减少了对冗长和重复的链接语法的需要。
以上是如何在 Laravel Eloquent 中有效地链接或分组多个 WHERE 子句?的详细内容。更多信息请关注PHP中文网其他相关文章!