I am mostly a Python/Django developer, so I might be a little off in the terminology, so I can’t find answer to this question:
How/where should I define custom model logic in C++/Qt?
Let say I have table Users with column date_birth and I want to add method getAge(), which simply calculate user’s age.
Where would I put this? Creating a subclass of QSqlRecord seems to me appropriate, but I haven’t found any references to this approach.
Second: Are there any conventions for subclassing QSql(Relational)?TableModel?
I’ve found similar snippet in many examples:
QSqlTableModel *model = new QSqlTableModel(parentObject, database);
model->setTable("employee");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Salary"));
but it seems redundant to define it everywhere I need it. Is it common to create subclasses such as UserTableModel and call all these methods in it’s constructor? Again, I haven’t found any references to it.
What you are trying to achieve is an objets/relational mapping.
So do it, it’s better not to make objects inherit from any SQL classes (in any object language)
You may create 2 classes: one for your “employee” and a factory object which will create this object by dealing with SQL ones:
With this kind of solution, your Employee class won’t depend on SQL classes. You can even chose to create handlers depending on any storage model.
or (more convenient for testing)
I suggest you have a look at Data Access Object pattern