[odb-users] ODB query

Boris Kolpackov boris at codesynthesis.com
Wed Sep 23 11:34:08 EDT 2015


Hi Tim,

Tim Tao <Tim.Tao at akunacapital.com> writes:

> Is there any way we can query table B by using condition ptr->name == "Tom"?

Yes, that's exactly how you would do it: A::ptr->name == "Tom".

As always, the manual is your friend. Quoting from Chapter 6, 
"Relationships":

"

We can also use data members from pointed-to objects in database queries
(Chapter 4, "Querying the Database"). For each pointer in a persistent class,
the query class defines a smart pointer-like member that contains members
corresponding to the data members in the pointed-to object. We can then use
the access via a pointer syntax (->) to refer to data members in pointed-to
objects. For example, the query class for the employee object contains the
employer member (its name is derived from the employer_ pointer) which in turn
contains the name member (its name is derived from the employer::name_ data
member of the pointed-to object). As a result, we can use the
query::employer->name expression while querying the database for the employee
objects. For example, the following transaction finds all the employees of
Example Inc that have the Doe last name:


typedef odb::query<employee> query;
typedef odb::result<employee> result;

session s;
transaction t (db.begin ());

result r (db.query<employee> (
  query::employer->name == "Example Inc" && query::last == "Doe"));

for (result::iterator i (r.begin ()); i != r.end (); ++i)
  cout << i->first_ << " " << i->last_ << endl;

t.commit ();
  

A query class member corresponding to a non-inverse (Section 6.2,
"Bidirectional Relationships") object pointer can also be used as a normal
member that has the id type of the pointed-to object. For example, the
following query locates all the employee objects that don't have an associated
employer object:

result r (db.query<employee> (query::employer.is_null ()));

"

Boris



More information about the odb-users mailing list