lundi 24 octobre 2016

Laravel: return model with relations

I'm trying to query a model with a relation.

My method:

public function getLabel($layerId)
{

    $labelGroups = Forum_label_group::with('labels')
        ->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;
}

The output:

[{"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":[]}]

As you can see, the label relation is empty.

Now I'm trying to query a single model instead off all:

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

the new output:

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

And as you can see now, everything is fine. The whole relation exists. Is there a problem with the initial query? The relation seems to be ok.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire