Natural primary key (id) and foreign key.
Added by Marcelo Antunes 11 months ago
I have that postgres database structure:
|--------------| |--------------------------------|
| table_a | | table_b |
|--------------| |--------------------------------|
| id bigint PK |-------------| id_a bigint PK FF table_a(id) |
| field1 text | | field3 text |
| field2 text | | field4 text |
|--------------| | idta bigint FK table_a(id) |
|--------------------------------|
As you can see, table_ba has a field that is PK and FK.
I tryed :
table_b.h
namespace Wt {
namespace Dbo {
template<>
struct dbo_traits<TableB> : dbo_default_traits
{
static const char *surrogateIdField() { return nullptr; }
};
}
}
class TableB
{
public:
TableB();
template <class Action>
void persist(Action &a)
{
Wt::Dbo::id(a,tableAPTR,">id_a",Wt::Dbo::NotNull);
Wt::Dbo::field(a,field3,"field3");
Wt::Dbo::field(a,field4,"field4");
}
private:
Wt::Dbo::ptr<TableA> tableAPTR;
Wt::WString field3;
Wt::WString field4;
};
table_a.h
class TableA
{
public:
TableA();
template <class Action>
void persist(Action &a)
{
Wt::Dbo::hasOne(a,tableBPTR,">id_a",Wt::Dbo::NotNull);
Wt::Dbo::field(a,field1,"field1");
Wt::Dbo::field(a,field2,"field2");
}
private:
Wt::Dbo::weak_ptr<TableB> tableBPTR;
Wt::WString field1;
Wt::WString field2;
};
But it gives me those errors:
cannot convert 'Wt::Dbo::ptr<TableA>' to 'cons IdType&' {aka 'const long long int&'}
Replies (1)
RE: Natural primary key (id) and foreign key. - Added by Matthias Van Ceulebroeck 5 months ago
Hello Marcelo,
I apologize for the very late response, it has been very busy lately.
You have an example you can follow from here:
https://www.webtoolkit.eu/wt/doc/tutorial/dbo.html#_specifying_a_natural_primary_key_that_is_also_a_foreign_key
You need to specify the IdType
of TableB
.
You can do this by:
template<>
struct dbo_traits<TableB> : public dbo_default_traits
{
using IdType = ptr<TableA>;
static IdType invalidId() {
return ptr<TableA>{};
}
}
``