背景
鉴于我们有以下两个表,其中 type_id 引用了 questionType 中的一行:
问题
id | type_id | description
---+---------+------------
1 | 1 | A nice question
.. | .. | ..
问题类型
id | name
---+----------------
1 | Multiple-choice
.. | ..
使用以下 Eloquent 模型:
class Question extends Model {
public function type() {
return $this->hasOne( 'QuestionType', 'id', 'type_id' );
}
}
class QuestionType extends Model {
}
问题 1
如何添加引用现有问题类型的新问题,而无需手动对 id 进行任何操作?例如,以下工作但在 imo 中很难看,因为我必须手动分配相应的问题类型 ID:
$q = new Question;
$q->type_id = 1; // Multiple-choice
$q->description = 'This is a multiple-choice question';
$q->save();
有人会认为有一种方法可以让 ORM 处理 id-assignment(使用 ORM 避免这样的事情不是重点吗?),类似于(这在 Eloquent ORM 中不起作用):
$q = new Question;
$q->type = QuestionType.where('name', '=', 'Multiple-choice');
$q->description = 'This is a multiple-choice question';
$q->save();
问题2
关于问题 1,我将如何添加一个引用新问题类型的新问题,而无需手动对 id 进行任何操作?同样,我想像以下内容:
$t = new QuestionType;
$t->name = 'Another type';
$q = new Question;
$q->type = $t;
$q->description = 'This is a multiple-choice question';
$q->save();
在这里我要
$q->save()
保存新的问题类型和问题(或类似的东西)。以下工作,但我再次自己分配我相信ORM应该处理的id:
$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();
我尝试过使用
save()
的不同组合。 , update()
没有运气的方法。我还找了attach()
存在于 hasMany
关系,但似乎在 hasOne
中缺失.
最佳答案
首先,您误解了您所指的关系。
这是您需要的:
// Question model
public function questionType()
{
return $this->belongsTo('QuestionType', 'type_id');
}
// QuestionType model
public function questions()
{
return $this->hasMany('Question', 'type_id');
}
然后你可以像这样将它们链接在一起:
$questionType = QuestionType::where(..)->first();
$question = new Question;
... // do something with it
// associate
$question->questionType()->associate($questionType);
// or the other way around - save new question and link to the type:
$questionType->questions()->save($question);
您也可以显式传递一个 id 来关联:
$question->type_id = $someTypeId;
$question->save();
你不能这样做:
$question->questionType = $someQuestionType;
因为 Eloquent 以这种方式处理模型属性,而不是关系。
问题2 :
$questionType = new QuestionType(['name' => 'multiple']);
$questionType->save();
$question = new Question([ ... some values ... ]);
// then either this way:
$questionType->questions()->save($question);
// or, again, the other way around:
$question->questionType()->associate($questionType);
$question->save();
关于laravel - 将 hasOne 模型附加到另一个 Laravel/Eloquent 模型而不指定 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26178049/