Laravel:返回带有关系的JSON模型

时间:2016-10-24 13:10:42

标签: php laravel-5.1

我试图用关系查询模型。

我的方法:

public function getLabel($layerId)
{

    $labelGroups = Forum_label_group::
        join('forum_layer_to_labels', function ($join) use ($layerId) {
            $join->on('forum_layer_to_labels.layerId', '=', 'forum_label_groups.id');
        })->with('labels')->get()->toJson();

    return $labelGroups;
}

输出:

[{"id":4,"name":"Demogruppe","description":"bla","required":1,"created_at":"2016-10-22 12:29:27","updated_at":"2016-10-22 12:29:27","labelGroupId":2,"layerId":2,"labels":[]},{"id":5,"name":"Demogruppe 2","description":"bla 2","required":0,"created_at":"2016-10-22 12:29:27","updated_at":"2016-10-22 12:29:27","labelGroupId":2,"layerId":3,"labels":[]}]

如您所见,标签关系为空。

现在我试图查询单个模型而不是全部:

public function getLabel($layerId)
{
    return Forum_label_group::with('labels')->first()->toJson();
}

新输出:

"{"id":2,"name":"Demogruppe","description":"bla","required":1,"created_at":"2016-10-22 12:29:27","updated_at":"2016-10-22 12:29:27","labels":[{"id":5,"title":"Demo rot","name":"demo-rot","typeId":3,"groupId":2,"created_at":"2016-10-22 12:29:47","updated_at":"2016-10-22 12:29:47"},{"id":6,"title":"Demoblau","name":"demoblau","typeId":1,"groupId":2,"created_at":"2016-10-22 12:30:03","updated_at":"2016-10-22 12:30:03"}]}"

正如你现在所看到的,一切都很好。整个关系存在。初始查询有问题吗?这种关系似乎没问题。

1 个答案:

答案 0 :(得分:1)

当然这是一个小问题;)

我忘记在查询中添加select()。原始id已被join()覆盖。因此,该方法尝试查询不存在的labelGroup

正确的查询:

public function getLabel($layerId)
    {
        $labelGroups = Forum_label_group::
            join('forum_layer_to_labels', function ($join) use ($layerId) {
                $join->on('forum_layer_to_labels.layerId', '=', 'forum_label_groups.id');
            })->select('forum_label_groups.*')->with('labels')
            ->get();

        return $labelGroups;
    }