【发布时间】:2014-10-03 11:20:47
【问题描述】:
背景
假设我们有以下两个表,其中 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 分配(不是要避免使用 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,我将如何添加一个引用 new 问题类型的新问题,而无需手动对 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() 方法的不同组合,但没有运气。我还查找了存在于hasMany 关系中但似乎在hasOne 中缺失的attach()。
【问题讨论】:
-
attach是belongsToMany(带枢轴的多对多)方法,因此它不适用于hasMany关系。hasOne/hasMany提供save方法,这很合逻辑,因为当你改变它的字段(外键)时你必须保存模型。
标签: laravel laravel-4 eloquent