将hasOne模型附加到另一个Laravel/Eloquent模型而不指定id

ole*_*ass 14 laravel eloquent laravel-4

背景

鉴于我们有以下两个表,其中type_id引用了questionType中的一行:

id | type_id | description
---+---------+------------
1  | 1       | A nice question
.. | ..      | ..
Run Code Online (Sandbox Code Playgroud)

问题类型

id | name 
---+----------------
1  | Multiple-choice 
.. | ..
Run Code Online (Sandbox Code Playgroud)

使用以下Eloquent模型:

class Question extends Model {
    public function type() {
        return $this->hasOne( 'QuestionType', 'id', 'type_id' );
    }
}

class QuestionType extends Model {
}
Run Code Online (Sandbox Code Playgroud)

问题1

如何添加引用现有问题类型的新问题,而无需手动执行任何有关ID的操作?例如,以下工作,但是丑陋的imo因为我必须手动分配相应的问题类型id:

$q = new Question;
$q->type_id = 1; // Multiple-choice
$q->description = 'This is a multiple-choice question';
$q->save();
Run Code Online (Sandbox Code Playgroud)

有人会认为有一种方法可以让ORM处理id-assignment(这不是用ORMs来避免这样的东西吗?),这有点像(这在Eloquent ORM中不起作用):

$q = new Question;
$q->type = QuestionType.where('name', '=', 'Multiple-choice');
$q->description = 'This is a multiple-choice question';
$q->save();
Run Code Online (Sandbox Code Playgroud)

问题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();
Run Code Online (Sandbox Code Playgroud)

在这里,我想$q->save()保存新的问题类型和问题(或类似的东西).

以下工作,但我再次分配我自己的ID,我相信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();
Run Code Online (Sandbox Code Playgroud)

我试着用不同的组合演奏save(),update()没有运气的方法.我也在寻找关系attach()中存在的hasMany但似乎缺少的关系hasOne.

Jar*_*zyk 17

首先,你误解了你所指的关系.

这就是你需要的:

// Question model
public function questionType()
{
  return $this->belongsTo('QuestionType', 'type_id');
}

// QuestionType model
public function questions()
{
  return $this->hasMany('Question', 'type_id');
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样把它们连在一起:

$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);
Run Code Online (Sandbox Code Playgroud)

您也可以显式传递ID以关联:

$question->type_id = $someTypeId;
$question->save();
Run Code Online (Sandbox Code Playgroud)

你不能这样做:

$question->questionType = $someQuestionType;
Run Code Online (Sandbox Code Playgroud)

为此,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();
Run Code Online (Sandbox Code Playgroud)