Attaching a hasOne model to another Laravel/Eloquent model without specifying id

折月煮酒 提交于 2019-12-04 23:39:12

First off, you misunderstood the relation you refer to.

Here's what you need:

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

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

then you can link them together like this:

$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);

You can explicitly pass an id to associate as well:

$question->type_id = $someTypeId;
$question->save();

You can't do this:

$question->questionType = $someQuestionType;

for this way Eloquent handles model attributes, not relations.


Question 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();

Answering question 1 for me both methods are good, you don't need to change anything.

Answering question 2 you should do it as you showed. ORM won't create automatically QuestionType until you use manually save method.

For example if you used code:

$t = new QuestionType;
$t->name = 'Another type';

$t2 = new QuestionType;
$t2->name = 'Another type 2';

$q = new Question;
$q->type = $t; // what here - $t2 or $t ?
$q->description = 'This is a multiple-choice question';
$q->save();

what ORM should decide? Question isn't connected to any of $t or $t2 so ORM won't decide it for you. You need to tell ORM what's the type.

I'm not an ORM/Eloquent expert but I think you expect too much from ORM. ORM shouldn't guess what you want to do. It help you manage relations or objects but it won't associate objects if you don't tell it to do so.

You could however try with mutator. You could add to your Question model:

public function setTypeAttribute($value)
{
    $value->save();
    $this->attributes['type_id'] = $value->id
}

and now it should be possible to use $q->type = $t; (However I haven't tested it)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!