[odb-users] ODB Query using relation

Boris Kolpackov boris at codesynthesis.com
Tue Jan 7 03:33:26 EST 2014


Hi Adrian,

Adrian Imboden <mail at adrianimboden.ch> writes:

> #pragma db object optimistic
> class User
> {
> public:
> 	#pragma db id auto
> 	uint32_t id = 0;
> 
> 	std::string name;
> 
> 	#pragma db column("emailToken")
> 	std::shared_ptr<Token> emailToken;
> 
> 	odb::vector<std::shared_ptr<Token>> authTokens
> 
> 	#pragma db version
> 	size_t version = 0;
> };
> 
> #pragma db object optimistic
> class Token
> {
> public:
> 	#pragma db id auto
> 	uint32_t id = 0;
> 
> 	std::string hash;
> 
> 	boost::posix_time::ptime expirationTime;
> 
> 	#pragma db version
> 	size_t version = 0;
> };
> 
> 1. Find all users that have an emailToken that has a given hash

This one is easy since you can use pointed-to objects in queries
(as discussed in the manual):

typedef odb::query<User> query;

db->query<User> (query::emailToken->hash == "1234");


> 2. Find all users that have at least one authToken with a given hash

This one is a bit trickier since ODB does not yet support querying
of containers. So here you will need to use a view:

#pragma db view object(User) object(Token = AuthToken: User::authTokens)
struct UserView
{
  #pragma db column(User::id)
  uint32_t id;
};

typedef odb::query<UserView> query;

db->query<UserView> (query::AuthToken::hash == "1234");

This will give you a list of User object ids that match the condition.
Given that, you can then load the actual objects. Alternatively, you
can pull the data members you are interested in directly in the view.


> PS: nice project by the way

Thanks, I am glad you are enjoying it.

Boris



More information about the odb-users mailing list