I’m developing a scheduling system and I’m using polymorphic associations to do it. I have several models that can be scheduled, but for now I’m focusing on two: Tasks and Vacations.
I have my Schedule model set up so it has a foreign_id and a class column. The idea being, a Schedule can belong to a Task, or a Vacation, based on the value of the class column:
// In SchedulesTable.php
$this->belongsTo('Tasks', [
'className' => 'Tasks',
'foreignKey' => 'foreign_id',
'conditions' => [
'Schedules.class' => 'Tasks',
],
]);
$this->belongsTo('Vacations', [
'className' => 'Vacations',
'foreignKey' => 'foreign_id',
'conditions' => [
'Schedules.class' => 'Vacations',
],
]);
// In TasksTable.php
$this->hasMany('Schedules', [
'className' => 'Schedules',
'foreignKey' => 'foreign_id',
'conditions' => [
'Schedules.class' => 'Tasks'
]
]);
// In VacationsTable.php
$this->hasMany('Schedules', [
'className' => 'Schedules',
'foreignKey' => 'foreign_id',
'conditions' => [
'Schedules.class' => 'Vacations'
]
]);
My issue occurs when I try to find Schedules, and contain both Tasks and Vacations, because when I do so, I get no results. When I change the joinType of the associations to “LEFT”, it works, but I can’t do any deeper containing (e.g. I can’t contain Tasks.Jobs, or Tasks.Users) because the Vacations model isn’t related to either Jobs or Users.
The only way I can see of getting it to work is to convert all the associations to “LEFT”, but that doesn’t strike me as a solution.
Am I going about this the right way, or is there a better solution?