Back
exists()
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.
If you don't pass in either of those, it will simply check if any record exists in the table.
// Checking if Joe exists in the database
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
if (model("user").exists(keyparams.key))
{
// Do something
}
// 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.)
comment = model("comment").findByKey(params.commentId);
commentHasAPost = comment.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.)
user = model("user").findByKey(params.userId);
userHasProfile = user.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.)
post = model("post").findByKey(params.postId);
postHasComments = post.hasComments();
Copied!