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

Boris Kolpackov boris at codesynthesis.com
Wed Jan 21 04:44:16 EST 2015


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.

Boris



More information about the odb-users mailing list