Back
findOne()
Fetches the first record found based on the WHERE
and ORDER BY
clauses.
With the default settings (i.e. the returnAs
argument set to object
), a model object will be returned if the record is found and the boolean value false
if not.
Instead of using the where
argument, you can create cleaner code by making use of a concept called Dynamic Finders.
// Getting the most recent order as an object from the database
order = model("order").findOne(order="datePurchased DESC");
// Using a dynamic finder to get the first person with the last name `Smith`. Same as calling `model("user").findOne(where"lastName='Smith'")`
person = model("user").findOneByLastName("Smith");
// Getting a specific user using a dynamic finder. Same as calling `model("user").findOne(where"email='someone@somewhere.com' AND password='mypass'")`
user = model("user").findOneByEmailAndPassword("someone@somewhere.com,mypass");
// If you have a `hasOne` association setup from `user` to `profile`, you can do a scoped call. (The `profile` method below will call `model("profile").findOne(where="userId=#user.id#")` internally)
user = model("user").findByKey(params.userId);
profile = user.profile();
// If you have a `hasMany` association setup from `post` to `comment`, you can do a scoped call. (The `findOneComment` method below will call `model("comment").findOne(where="postId=#post.id#")` internally)
post = model("post").findByKey(params.postId);
comment = post.findOneComment(where="text='I Love Wheels!'");
Copied!