Can a Model be a child and a parent at the same time?
mossadal opened this issue · comments
I realize this might not the best database design, but I wonder if your package could doing something with this?
I have a database with the following simplified tables:
questions |
---|
type |
answers |
---|
question_id |
subtype |
and relationships
Question::hasOne(Answer)
Answer::belongsTo(Question)
I.e. questions can have several types, and each specific type of question has a subtype via the subtype field on Answer. The subtypes are only unique within a question type.
I was trying to setup a hierarchy of sti classes like:
class Question extends Model {
use HasChildren;
protected $childTypes = [
1 => MultipleChoiceQuestion::class,
2 => NumberQuestion::class,
...
];
}
class NumberQuestion extends Question
{
use HasParent;
public function answer()
{
return $this->hasOne(NumberAnswer::class);
}
}
class Answer extends Model {
use HasChildren;
}
class NumberAnswer extends Answer {
use HasParent;
user HasChildren;
protected $childColumn = 'subtype';
protected $childTypes = [
1 => NumberVariant1::class,
2 => NumberVariant2::class,
...
];
}
class NumberVariant1 extends NumberAnswer
{
use HasParent;
}
However, this fails, since both HasParent
and HasChildren
contain conflicting getClassNameForRelationships
methods. Is there a way to do this, or something similar without changing the database layout?
I found a way to make it work, put explicit column names in Answer
and remove the HasChildren
, HasParent
relation between Answer
and AnswerNumber
did the trick.