Background
Given that we have the following two tables, where type_id refers to the specified Type string:
Question
id | type_id | description ---+---------+------------ 1 | 1 | A nice question .. | .. | ..
questionType
id | name ---+---------------- 1 | Multiple-choice .. | ..
with the following worm models:
class Question extends Model { public function type() { return $this->hasOne( 'QuestionType', 'id', 'type_id' ); } } class QuestionType extends Model { }
Question 1
How to add a new question that refers to an existing question type without manual action with identifiers? For example, the following works, but is ugly imo, since I have to manually assign the appropriate question type identifier:
$q = new Question; $q->type_id = 1;
One would think that there is a way to allow ORM to handle id assignments (shouldn't things be avoided with ORM?), Something like this (this does not work in Eloquent ORM):
$q = new Question; $q->type = QuestionType.where('name', '=', 'Multiple-choice'); $q->description = 'This is a multiple-choice question'; $q->save();
Question 2
In relation to question 1, how can I add a new question that refers to a new type of question, without manual action with identifiers? In the same way, I imagine something like:
$t = new QuestionType; $t->name = 'Another type'; $q = new Question; $q->type = $t; $q->description = 'This is a multiple-choice question'; $q->save();
Here I would like $q->save() to save both the new question type and the question (or something similar).
The following steps, but again, I assign the identifier itself, which, in my opinion, should handle the ORM:
$t = new QuestionType; $t->name = 'Another type'; $t->save(); $q = new Question; $q->type = $t->id; $q->description = 'This is a multiple-choice question'; $q->save();
I tried playing with various combinations of save() , update() methods with no luck. I also searched for attach() , which exists in the hasMany relationship but seems to be missing in hasOne .