【问题标题】:Why laravel eloquont relation returning empty array为什么 laravel 雄辩的关系返回空数组
【发布时间】:2021-06-20 23:58:13
【问题描述】:
My Relationship is 

    public function QuestionOptions()
    {
        return $this->hasMany('App\Models\QuestionOption','QuestionId');
    }

but when i am running this query 

        $builder = Question::select([
            'id', 'type', 'questionText', 'note', 'solutionText',
        ])->with('QuestionOptions')
        ->orderByRaw("RAND()")
        ->skip(0)
        ->take(1)
        ->get()
        ->toArray();

i am getting this 

    {
        "id": 1,
        "type": "multiple",
        "questionText": "2 + 2 = ?",
        "note": null,
        "solutionText": null,
        "question_options": []
    },

so i want to know why i am getting question_options empty is there any problem in my query?

更改后:-

我尝试更改我的查询并删除了选择,所以现在我的查询看起来像这样

        $builder = Question::with('QuestionOptions')
        ->orderByRaw("RAND()")
        ->skip(0)
        ->take(1)
        ->get()
        ->toArray();

运行查询后,我的输出如下所示,我得到了两个表的所有字段,这没问题,但现在出现了问题,我应该如何只获取特定字段

   [{
        "Id": 2,
        "UID": "123456789098765",
        "Type": "single",
        "Rank": 2,
        "QuestionText": "4 + 4 = ?",
        "TotalMarks": 5,
        "Note": null,
        "SolutionText": null,
        "Status": "active",
        "TimeStamp": "2020-11-17 12:04:18",
        "NegativeMark": 2,
        "TestId": 4,
        "question_options": [
            {
                "Id": 13,
                "OptionText": "5",
                "Rank": 1,
                "IsAnswer": "no",
                "Status": "deactive",
                "TimeStamp": "2020-11-17 12:59:14",
                "QuestionId": 2
            },]

【问题讨论】:

  • 迁移是什么样的?问题和/或 question_options 的外键字段的名称是什么?
  • 我的问题表包含 -> id,type,rank,questionText,totalMarks,status,testId 我的 questionOption 表包含 -> id,optionText,rank,IsAnswer,status,questionId

标签: sql laravel eloquent relationship has-many


【解决方案1】:

试试这个,


       $builder = Question::with('QuestionOptions')
        ->orderByRaw("RAND()")
        ->skip(0)
        ->take(1)
        ->get(['id', 'type', 'questionText', 'note', 'solutionText'])
        ->toArray();

【讨论】:

  • 但 questionId 不在表中,所以会抛出错误
  • Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'QuestionId'在'字段列表' (SQL:从test_question中选择idtypequestionTextnotesolutionTextQuestionId
  • 那是我的错,你可以在 get() 中指定字段的名称。你只得到特定的字段。请参阅我更新的答案。试试这个。我希望这是有效的。
  • 感谢您的努力,但没有帮助:(
  • 实际上当我尝试获取特定列时出现问题,我尝试了相同的方法而不使用 select 然后我从两个表中获取了所有字段
猜你喜欢
  • 2018-06-19
  • 2015-12-17
  • 2013-04-10
  • 2018-04-11
  • 2015-03-14
  • 2018-11-28
  • 2015-01-11
  • 2021-06-03
  • 2020-03-26
相关资源
最近更新 更多