You are viewing documentation for v1.0.x. Change

exists()

Description

Checks if a record exists in the table. You can pass in either a primary key value to the key argument or a string to the where argument.

Function Syntax

exists([ key, where, reload, parameterize ])

Parameters

Parameter Type Required Default Description
key any No Primary key value(s) of the record to fetch. Separate with comma if passing in multiple primary key values. Accepts a string, list or a numeric value.
where string No This argument maps to the WHERE clause of the query. The following operators are supported: =, <>, <, <=, >, >=, LIKE, AND, and OR (note that the key words have to be written in upper case). You can also use parentheses to group statements. You do not have to specify the table name(s), Wheels will do that for you.
reload boolean No false Set to true to force Wheels to query the database even though an identical query has been run in the same request (the default in Wheels is to get the second query from the cache).
parameterize any No true Accepts a boolean value or a string. Set to true to use cfqueryparam on all columns or pass in a list of property names to use cfqueryparam on those only.

Examples

<!--- Checking if Joe exists in the database --->
<cfset result = model("user").exists(where="firstName='Joe'")>

<!--- Checking if a specific user exists based on a primary key valued passed in through the URL/form in an if statement --->
<cfif model("user").exists(keyparams.key)>
    <!--- Do something... --->
</cfif>

<!--- If you have a `belongsTo` association setup from `comment` to `post` you can do a scoped call (the `hasPost` method below will call `model("post").exists(comment.postId)` internally) --->
<cfset aComment = model("comment").findByKey(params.commentId)>
<cfset commentHasAPost = aComment.hasPost()>

<!--- If you have a `hasOne` association setup from `user` to `profile` you can do a scoped call (the `hasProfile` method below will call `model("profile").exists(where="userId=#user.id#")` internally) --->
<cfset aUser = model("user").findByKey(params.userId)>
<cfset userHasProfile = aUser.hasProfile()>

<!--- If you have a `hasMany` association setup from `post` to `comment` you can do a scoped call (the `hasComments` method below will call `model("comment").exists(where="postid=#post.id#")` internally) --->
<cfset aPost = model("post").findByKey(params.postId)>
<cfset postHasComments = aPost.hasComments()>