【发布时间】: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