Laravel雄辩的关系

时间:2014-05-02 00:07:26

标签: php laravel laravel-4

我有一个问题表和另一个包含Answers的表。一个问题有很多答案,答案属于一个问题。这些关系已在问答模型中定义,并按预期工作。

但是,当我试图通过答案得到一堆问题时,Eloquent会返回一个空数组。

return Question::with('answers')
                ->where('category_id', $input['category'])
                ->take($input['num_questions'])
                ->orderBy(DB::raw('RAND()'))
                ->get();

我收到以下回复......

{
"id": "1",
"category_id": "1",
"question": "Why did the chicken cross the road?",
"feedback": "Why did you ask that?",
"created_at": "2014-04-24 16:57:48",
"updated_at": "2014-04-24 16:57:48",
"answers": []
},
{
"id": "2",
"category_id": "1",
"question": "How awesome is Laravel?",
"feedback": "That's debatable.",
"created_at": "2014-04-24 16:57:48",
"updated_at": "2014-04-24 16:57:48",
"answers": []
}

打印原始查询时,我看到以下内容......

{
"query": "select * from `questions` where `category_id` = ? order by RAND() asc",
"bindings": [
    "1"
],
"time": 2.11
},
{
"query": "select `id`, `choice`, `correct` from `answers` where `answers`.`question_id` in (?, ?, ?, ?)",
"bindings": [
    "3",
    "4",
    "1",
    "2"
],
"time": 0.92
}

当我手动运行这些查询时,我会看到答案,但由于某些原因,laravel会显示一个空数组。为什么?我在这里做错了什么?

2 个答案:

答案 0 :(得分:1)

我手动选择了我想在模型中返回的字段。当您选择多行而不是单行时,这显然会中断。

    return $this->hasMany('Answers')->select(array('id', 'choice'));

从模型中删除 - > select()代码修复它。

答案 1 :(得分:1)

首先从模型中删除 - > select()代码,然后执行:

return Question::with(array('answers'=>function($query)
            {
                $query->select(array('id', 'choice','question_id')); // question_id is mandatory because Laravel need it for mapping
            }))
            ->where('category_id', $input['category'])
            ->take($input['num_questions'])
            ->orderBy(DB::raw('RAND()'))
            ->get();