[odb-users] one-to-one relationship with shared primary keys

Paul Harrison paul.harrison at manchester.ac.uk
Wed Jan 21 09:53:17 EST 2015


On 2015-01 -21, at 09:44, Boris Kolpackov <boris at codesynthesis.com> wrote:

> Hi Paul,
> 
> Paul Harrison <paul.harrison at manchester.ac.uk> writes:
> 
>> I have several tables with the same primary key, and a one-to-one
>> relationship between instances in the tables. I have been trying
>> to find a way to be able to have the object for one the tables
>> include shared pointers to the corresponding objects in the other
>> tables without any extra columns being used as foreign keys, but
>> have not been able to find a method of doing this with ODB - is
>> there a trick that I am missing?
> 
> You can use a database operation callback to implement this quite
> easily. Here the outline:
> 
> #pragma db object
> struct object1
> {
>  #pragma db id
>  int id;
> 
>  ...
> };
> 
> #include <odb/callback.hxx>
> 
> #pragma db object callback(init)
> struct object2
> {
>  #pragma db id
>  int id; // Also, implicitly, a foreign key to object1.
> 
>  ...
> 
>  #pragma db transient
>  std::shared_ptr<object1> obj1;
> 
>  void init (odb::callback_event e, odb::database& db)
>  {
>    if (e == odb::callback_event::post_load) 
>      obj1 = db.load<object1> (id);
>  }
> };
> 
> See Section 14.1.7, "callback" for more details on database operation
> callbacks.

Great - this does exactly what I want and prevents the need for db access code having to leak into parts of my code that should not have to know about the database.

thanks,
	Paul.





More information about the odb-users mailing list