1

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

My method:

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;
}

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.

3
  • 1
    Any reason you're using ::with('labels') and ->with('labels') in the same eloquent statement? Commented Oct 24, 2016 at 13:19
  • Whoops, you're right! The ::with('labels') was an obsolete debugging test. I've edited the question. Commented Oct 24, 2016 at 13:26
  • No worries; I don't think it affects anything really, but it was certainly odd to see. Commented Oct 24, 2016 at 13:27

1 Answer 1

1

And of course it was an small issue ;)

I forgot to add a select() on my query. The original id has been overwritten by the join(). So the method tried to query an labelGroup that doesn't exist.

The correct query:

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.