【问题标题】:Laravel Relationship with multiple tableLaravel与多个表的关系
【发布时间】:2018-10-20 22:32:01
【问题描述】:

我正在创建一个在线测试门户。

表结构是

  1. live_test (收集测试的不同数据) - {id, title, instructions, total_questions, is_published, per_question_mark, per_question_negative_mark, duration}
  2. questions(存储问题)- {id, live_test_id, index, type, question, option_1, option_2, option_3, option_4, solution}
  3. live_test_user (判断用户是否已经做过测试) - {id, user_id, total_mark}
  4. live_test_answers(查明用户是否给出了正确答案 - 供以后分析) - {id, question_id, user_id, answer_given, is_correct}

这是完美的工作。我只是想知道我们可以建立任何关系以便我们可以执行

$question->user->answer

或者,类似的,

$user->question->answer

轻松发现用户是否对特定问题给出了正确答案。

每个用户的每个问题在live_test_answers中只有一个条目。

【问题讨论】:

  • 我已阅读文档。没有这样的,我只是想知道有没有人做过这种关系。
  • 阅读Eager loading,特别是在Nested Eager Loading
  • @apokryfos 这需要模型之间的关系。这就是我要问的是这里是否存在任何关系。我将有问答的对象,我可以轻松地做到 $answer = Question::where(['question_id' => $question_id, 'user_id' => $user_id])->first();找到给定的答案。我只是想知道这里是否存在任何关系。
  • @apokryfos live_test_answer 表同时包含 id、user_id 和 question_id。

标签: php laravel eloquent


【解决方案1】:

您需要查看您的live_test_answers 表才能获得答案和问题。

// For the example let's fetch the first answer the user gave
$answer = $user->answers()->first();
// Now let's fetch the question related to the answer
$question = $answer->question;

// Now you can check the answer for the question, something like
$isCorrect = $answer->answer == $question->answer;

【讨论】:

  • 其实,我想找到给定问题的答案。你的答案正好相反。
  • 您可以通过问题id和用户id$answer = Answer::where('user_id', $userId)->where('question_id')->first()查询答案
  • $answer = Question::where(['question_id' => $question_id, 'user_id' => $user_id])->first(); ,正如我在问题中提到的那样,这工作正常。我只是想知道,这里是否可以存在任何关系,所以我可以玩这些对象..
猜你喜欢
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 2018-10-05
  • 2020-06-12
  • 1970-01-01
  • 2019-06-23
  • 2021-01-27
  • 2021-01-14
相关资源
最近更新 更多