0

我尝试更新具有关系的 2 个模型的值,但我的方法似乎不太“Laravel 方式”,有更好的方法吗?

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

从模型:

public function questions()
{
    return $this->belongsTo(Question::class);
}

public function question_topics()
{
    return $this->hasOne(QuestionTopics::class, 'id');
}
4

1 回答 1

1

您需要首先将关系中的参数添加为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,
]); 
于 2020-03-25T06:20:41.593 回答