Reputation: 1513
I try to update value for 2 models with relationship, but my approach don't seem too "Laravel way", any better way to do this?
$question = new Question();
$question->where('id', $id)->update([
'free_text' => $request->free_text,
'title' => $request->title,
//here I have a topics_id
]);
$question_topics = new QuestionTopics();
$question_topics->where('id', $request->topics_id)->update([
'best_match_topic' => $request->best_match_topic,
'topic_1' => $request->topic_1,
'topic_2' => $request->topic_2,
'topic_3' => $request->topic_3,
]);
From models:
public function questions()
{
return $this->belongsTo(Question::class);
}
public function question_topics()
{
return $this->hasOne(QuestionTopics::class, 'id');
}
Upvotes: 0
Views: 41
Reputation: 15296
You need to add param in relationship first as topics_id.
public function question_topics()
{
return $this->hasOne(QuestionTopics::class,'topics_id', 'id');
}
$question = Question::find($id)
$question->update([
'free_text' => $request->free_text,
'title' => $request->title,
]);
$question->question_topics()->update([
'best_match_topic' => $request->best_match_topic,
'topic_1' => $request->topic_1,
'topic_2' => $request->topic_2,
'topic_3' => $request->topic_3,
]);
Upvotes: 1