-
Notifications
You must be signed in to change notification settings - Fork 27
Query interface
y-yoshinoya edited this page Feb 13, 2013
·
43 revisions
Code examples throughout this guide will refer to one or more of the following models:
package models
case class Client(name: String, age: Int) extends ActiveRecord {
lazy val orders = hasMany[Order]
lazy val roles = hasAndBelongToMany[Role]
}
object Client extends ActiveRecordCompanion[Client]
case class Order(price: Int) extends ActiveRecord {
lazy val client = belongsTo[Client]
}
object Order extends ActiveRecordCompanion[Order]
case class Role(name: String) extends ActiveRecord {
lazy val clients = hasAndBelongToMany[Role]
}
object Role extends ActiveRecordCompanion[Role]
object Tables extends ActiveRecordTables {
val clients = table[Client]
val orders = table[Order]
val roles = table[Role]
}
Using Model.find(primaryKey)
, you can retrieve the object Option[Model]
corresponding to the specified primary key that matches any supplied options. For example:
val client = Client.find(10)
// => Some(Client) or None
Note : This method is not type-safe yet. Use the
Model#where
method instead.
Using Model.findBy((key, value)*)
finds the first record by multiple fieldnames and values. For example:
val john = Client.findBy("name", "john")
// => Some(Client("john")) or None
val john25 = Client.findBy(("name", "john"), ("age", 25))
// => Some(Client("john", 25)) or None
Note : This method is not type-safe yet.
Using Model.findByOrCreate(model, fields*)
returns either the record that already exists or the new record. For example:
val client = Client.findByOrCreate(Client("john", 25), "name", "age")
// => found Client("john", 25) or created Client("john", 25)
Defined implicit conversion from companion model Model
to scala.collection.Iterable
.
For example:
val client1 = Client.head
// => First client or java.util.NoSuchElementException
val client2 = Client.headOption
// => First Option[Client] or None
val client3 = Client.lastOption
// => Last Option[Client] or None
val (adults, children) = Client.partition(_.age >= 20)
// => parts of clients
No implement yet.