For each table I have createdAt and updatedAt and it s redondant to set it in each beforeCreate/Update It is possible to add a static option to add it automatically ex:
class Foo extends Model {
static $createdAt = 'tableName'
static $UpdatedAt = 'tableName'
}
Basic OOP saves you here. Just create a base class:
class ModelBase extends Model {
$beforeUpdate() {
this.updatedAt = new Date().toISOString();
}
$beforeInsert() {
this.createdAt = new Date().toISOString();
}
}
and then inherit all your models from ModelBase instead of Model. This way the code is only in once place.
but I need to call super in this case
So you have $beforeUpdate and $beforeInsert implemented for all your models to do different things in addition to settings the timestamps? If they do common stuff, just move them to the parent class. If they do different things and you cannot move the implementation to the parent class then yes, you need to call super.
You do know that you don't need to implement the $before methods if they do nothing but call super() right? :)
I always add those timestamps in the database using triggers. Have you considered that?
Yeah I know for super, but I have to set a random pid in beforeInsert for example but I go look for triggers
Basic OOP saves you here. Just create a base class:
class ModelBase extends Model { $beforeUpdate() { this.updatedAt = new Date().toISOString(); } $beforeInsert() { this.createdAt = new Date().toISOString(); } }and then inherit all your models from
ModelBaseinstead ofModel. This way the code is only in once place.
I think its best to remove the createdAt field when updating
$beforeUpdate() {
delete this.createdAt;
this.updatedAt = new Date().toISOString();
}
Most helpful comment
Basic OOP saves you here. Just create a base class:
and then inherit all your models from
ModelBaseinstead ofModel. This way the code is only in once place.