检索 JSON 输出的数据和关系

Retrieving data and relationships for JSON output

我对这一切都是陌生的,我正在努力思考 Laravel。我有两个模型设置和一个枢轴 table。我正在尝试以下列格式输出一些 JSON:

[
    {
        "question": "somequestiongoeshere",
        "tags": [
            "tag1",
            "tag2"
        ]
    },
    {
        "question": "somequestiongoeshere",
        "tags": [
            "tag1",
            "tag2"
        ]
    }
]

我只能输出标签或问题,但不能输出上述格式。任何指导将不胜感激。

Question.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Question extends Model {

    public function tags() {
        return $this->hasMany('App\Tag');
    }

}

Tag.php

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model {

    public function questions() {
        return $this->hasMany('App\Question');
    }

}

控制器

public function index() {
    return Question::all();
}

Eloquent,默认情况下,在关系被调用之前不加载关系(延迟加载)。您需要指定要加载的关系,或者 'eager load' 它们(与延迟加载相反)。例如:

$questions = Question::with('tags')->get();

查看更多here.