Back
findByKey()
The findByKey() function retrieves a single record from the database using its primary key value and returns it as an object by default. If the record is not found, it returns false, making it easy to handle missing data gracefully. You can also control what columns are returned using the select argument, include related associations, or override the return format to a query, struct, or even raw SQL. Since it accepts the same options as other read functions like findOne(), you can apply caching, indexing, and even include soft-deleted records when needed.
1. Getting the author with the primary key value `99` as an object
auth = model("author").findByKey(99);
2. Getting an author based on a form/URL value and then checking if it was found
auth = model("author").findByKey(params.key);
if(!isObject(auth)){
flashInsert(message="Author #params.key# was not found");
redirectTo(back=true);
}
3. If you have a `belongsTo` association setup from `comment` to `post`, you can do a scoped call. (The `post` method below will call `model("post").findByKey(comment.postId)` internally)
comment = model("comment").findByKey(params.commentId);
post = comment.post();
Copied!