Skip to content

Model Class

findAll()

findAll() — returns any

Available in: model Category: Read Functions

Returns records from the database table mapped to this model according to the arguments passed in (use the where argument to decide which records to get, use the order argument to set the order in which those records should be returned, and so on). The records will be returned as either a cfquery result set, an array of objects, or an array of structs (depending on what the returnAs argument is set to).

NameTypeRequiredDefaultDescription
wherestringno—Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. Nested queries not allowed. You do not need to specify the table name(s); Wheels will do that for you.
orderstringno—Maps to the ORDER BY clause of the query. You do not need to specify the table name(s); Wheels will do that for you.
groupstringno—Maps to the GROUP BY clause of the query. You do not need to specify the table name(s); Wheels will do that for you.
selectstringno—Determines how the SELECT clause for the query used to return data will look. You can pass in a list of the properties (which map to columns) that you want returned from your table(s). If you don’t set this argument at all, Wheels will select all properties from your table(s). If you specify a table name (e.g. users.email) or alias a column (e.g. fn AS firstName) in the list, then the entire list will be passed through unchanged and used in the SELECT clause of the query. By default, all column names in tables joined via the include argument will be prepended with the singular version of the included table name.
includeCalculatedstringno—List of calculated property names (declared via property(name="...", sql="...", select=false)) to additively opt into this finder’s SELECT clause. Unlike select, this does not replace the default column list — the named calculated properties are merged on top of all default columns, so the rest of the record is still returned. Useful for pulling a select=false computed property back in on a single finder without spelling out every other column. Unknown names throw Wheels.CalculatedPropertyNotFound in development/testing and are ignored in production.
distinctbooleannofalseWhether to add the DISTINCT keyword to your SELECT clause. Wheels will, when necessary, add this automatically (when using pagination and a hasMany association is used in the include argument, to name one example).
includestringno—Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
maxRowsnumericno-1Maximum number of records to retrieve. Passed on to the maxRows cfquery attribute. The default, -1, means that all records will be retrieved.
pagenumericno0If you want to paginate records, you can do so by specifying a page number here. For example, getting records 11-20 would be page number 2 when perPage is kept at the default setting (10 records per page). The default, 0, means that records won’t be paginated and that the perPage and count arguments will be ignored.
perPagenumericno10When using pagination, you can specify how many records you want to fetch per page here. This argument is only used when the page argument has been passed in.
countnumericno0When using pagination and you know in advance how many records you want to paginate through, you can pass in that value here. Doing so will prevent Wheels from running a COUNT query to get this value. This argument is only used when the page argument has been passed in.
handlestringnoqueryHandle to use for the query. This is used when you’re paginating multiple queries and need to reference them individually in the paginationLinks() function. It’s also used to set the name of the query in the debug output (which otherwise defaults to userFindAllQuery for example).
cacheanyno—If you want to cache the query, you can do so by specifying the number of minutes you want to cache the query for here. If you set it to true, the default cache time will be used (60 minutes).
reloadbooleannofalseSet to true to force Wheels to query the database even though an identical query for this model may have been run in the same request. (The default in Wheels is to get the second query from the model’s request-level cache.)
parameterizeanynotrueSet to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
returnAsstringnoquerySet to objects to return an array of objects, set to structs (or its alias array) to return an array of structs, set to query to return a query result set, or set to ‘sql’ to return the executed SQL query as a string.
returnIncludedbooleannotrueWhen returnAs is set to objects, you can set this argument to false to prevent returning objects fetched from associations specified in the include argument. This is useful when you only need to include associations for use in the WHERE clause only and want to avoid the performance hit that comes with object creation.
callbacksbooleannotrueSet to false to disable callbacks for this method.
includeSoftDeletesbooleannofalseSet to true to include soft-deleted records in the queries that this method runs.
useIndexstructno[runtime expression]If you want to specify table index hints, pass in a structure of index names using your model names as the structure keys. Eg: {user="idx_users", post="idx_posts"}. This feature is only supported by MySQL and SQL Server.
dataSourcestringno[runtime expression]Override the default datasource
$limitnumericno0
$offsetnumericno0
$forUpdatebooleannofalse
$useRequestCachebooleannotrue
// 1. Get all users ordered by last name
users = model("user").findAll(order="lastName ASC");

// 2. Get only 5 users in a random order
fiveRandomUsers = model("user").findAll(maxRows=5, order="random");

// 3. Include a belongsTo association and filter with a WHERE clause
articles = model("article").findAll(include="author", where="published=1", order="createdAt DESC");

// 4. Include a hasMany association in the opposite direction
bobsArticles = model("author").findAll(include="articles", where="firstName='Bob'");

// 5. Use pagination (records 26-50) with a nested include (song belongsTo album, album belongsTo artist)
songs = model("song").findAll(include="album(artist)", page=2, perPage=25);

// 6. Return results as an array of model objects instead of a query
activeUsers = model("user").findAll(where="active=1", order="lastName ASC", returnAs="objects");
for (user in activeUsers) {
	writeOutput(user.firstName & " " & user.lastName);
}

// 7. Return results as an array of structs
userStructs = model("user").findAll(where="active=1", returnAs="structs");

// 8. Use a dynamic finder to get all books released in a certain year
// (same as model("book").findAll(where="releaseYear=#params.year#"))
books = model("book").findAllByReleaseYear(params.year);

// 9. Use a dynamic finder with multiple criteria
// (same as model("book").findAll(where="releaseYear=#params.year# AND type='#params.type#'"))
books = model("book").findAllByReleaseYearAndType("#params.year#,#params.type#");

// 10. Use a scoped call via a hasMany association (calls findAll internally with a where clause)
post = model("post").findByKey(params.postId);
comments = post.comments();

// 11. Use GROUP BY with a calculated property (generates HAVING instead of WHERE)
// Order model has a calculated property: property(name="totalAmount", sql="SUM(amount)")
ids = model("order").findAll(group="productId", where="totalAmount > 1000", select="productId");

// 12. Include soft-deleted records
allUsers = model("user").findAll(includeSoftDeletes=true, order="lastName ASC");

// 13. Cache the query results for 10 minutes
cachedUsers = model("user").findAll(where="active=1", cache=10);

// 14. Return the generated SQL string instead of running the query
sql = model("user").findAll(where="active=1", order="lastName ASC", returnAs="sql");
// sql -> "SELECT ... FROM users WHERE active = 1 ORDER BY last_name ASC"

// 15. Use index hints (MySQL and SQL Server only)
indexes = {
	author="idx_authors_name",
	post="idx_posts_created"
};
posts = model("author").findAll(
	where="firstName LIKE '#params.q#%' OR subject LIKE '#params.q#%'",
	include="posts",
	useIndex=indexes
);