[odb-users] Many-to-many adding values to join table.
Boris Kolpackov
boris at codesynthesis.com
Sat Jul 9 15:42:16 EDT 2011
Hi Rafael,
Rafael Pena <pena.rd at gmail.com> writes:
> I am a bit confused about the many-to-many relationship. How do I add the
> relationship when when both entities already exist?
> These are my classes:
>
> class PartData {
>
> [...]
>
> #pragma db id auto
> //other fields go here
>
> unsigned long partdataid;
>
> #pragma db not_null inverse(parts)
> std::vector<weak_ptr<TestData> > tests;
> };
>
> class TestData {
>
> [...]
>
> #pragma db id auto
> unsigned long testdataid;
> //other fields go here
> #pragma db not_null unordered
> std::vector<shared_ptr<PartData> > parts;
> };
>
> When both already exist and I add one (parts.push_back()) to the other. How
> do I add to the join table?
You will need to modify the direct (non-inverse) object (TestData) and
update its state in the database, for example:
shared_ptr<PartData> pd = ...; // Already persisted object.
shared_ptr<TestData> td = ...; // Already persisted object.
td->parts.push_back (pd);
db->update (td);
You should probably also update the non-inverse side so that your
in-memory model is consistent.
> Anybody have an example?
The example that shows how to work with bi-directional relationships
is called 'inverse'.
> Right now I am just running an insert query:
>
> db->execute("insert into TestData_parts values (" + testid+","+
> partdataids.str() + ")");
No, this is definitely not the way to do it.
Boris
More information about the odb-users
mailing list