Início / Optitravel / Models
findWhere(array $conditions, array $columns = ['*'], array $options = [])
- findWhere(array $conditions, array $columns = ['*'], array $options = [])
- Parameters
- Example
- Supported operators
- Error handling
This method retrieves records from the database based on a set of conditions and filters. It allows for more flexible querying than the basic find and findBy methods by letting you define custom conditions, sort order, and limits.
You can use this method to apply complex queries like "status = 'A' and name LIKE '%test%'" or filter by ranges with "BETWEEN". It also supports options for sorting (orderBy), limiting the number of results (limit), and applying an offset (offset).
Parameters
- $conditions – An array of condition arrays, where each condition is in the format [column, operator, value].Example:
[
['status', '=', 'A'],
['name', 'LIKE', '%test%'],
['id', 'IN', [1, 2, 3]],
['created_at', 'BETWEEN', ['2024-01-01', '2024-12-31']]
]
-
$columns (optional) – An array of column names to retrieve. If set to ['*'] or left empty, all allowed columns will be returned.
-
$options (optional) – An array of additional options like orderBy, limit, and offset:
-
orderBy – The column and direction (e.g., 'name ASC' or 'created_at DESC').
-
limit – The maximum number of results to return.
-
offset – The number of records to skip before starting the result set.
Returns:
An array of objects representing the records that match the conditions.
Example
use \App\Models\User;
$user = new User();
$users = $user->findWhere(
[
['status', '=', 'A'],
['name', 'LIKE', '%test%']
],
['id', 'name'],
['orderBy' => 'name ASC', 'limit' => 10]
);
foreach ($users as $user) {
echo $user->name;
}
Supported operators
The following operators are supported: - =, !=, <>, <, >, <=, >=, LIKE - IN – expects an array of values - BETWEEN – expects an array with exactly two values ([start, end])
Error handling
-
An exception is thrown if no conditions are provided.
-
Each condition must be an array with exactly three elements: [column, operator, value].
-
Only columns listed in allowedColumns can be used in conditions or in the orderBy option.
-
The IN and BETWEEN operators require values in array format. Invalid formats will trigger an exception.
-
Sorting direction must be either 'ASC' or 'DESC'.
↑ (Última atualização: 13/05/2025)