【问题标题】:Laravel: return JSON model with relationLaravel:返回具有关系的 JSON 模型
【发布时间】:2016-10-24 13:10:42
【问题描述】:

我正在尝试查询具有关系的模型。

我的方法:

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"}]}"

正如您现在所看到的,一切都很好。整个关系存在。初始查询有问题吗?关系似乎还可以。

【问题讨论】:

  • 你有什么理由在同一个雄辩的陈述中使用::with('labels')->with('labels')
  • 哎呀,你是对的! ::with('labels') 是一个过时的调试测试。我已经编辑了问题。
  • 不用担心;我认为它不会真正影响任何事情,但看到它肯定很奇怪。

标签: php laravel-5.1


【解决方案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;
    }

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 2017-11-23
    • 2020-11-15
    • 2017-07-16
    • 2015-04-18
    • 1970-01-01
    • 2020-09-08
    • 2014-10-15
    • 2013-07-04
    相关资源
    最近更新 更多