1

I was wondering if it's possibly to order any of the sub-models while lazy eager loading? At the moment I have

Item::findOrFail($id)
     ->load('sections', 'level', 'category', 'tags', 'relatedItems');

I would like the tags to order by name so I was wondering if something like

Item::findOrFail($id)
    ->load('sections', 'level', 'category', 'tags', 'relatedItems')
    ->orderBy('tag.name');

would be possible.

I see other examples on here using 'with' but I can't seem to get that loading with a singular base model.

Thanks

0

1 Answer 1

3

You use the same syntax as with eager load constraints,

$item = Item::findOrFail($id);
$item->load(array('tags' => function($query) {
    $query->orderBy('tag.name');
}));

In your example you can also use with() instead of load(). The latter is used when you want to load into an existing model, as in my example, though I suppose that is splitting hairs!

Sign up to request clarification or add additional context in comments.

2 Comments

That doesn't seem to work for me. If I use 'load', then the Item is not found. If I use 'with', then the item is found, but not with any tags. In the item model I have public function tags() { return $this->belongsToMany('Tag', 'tag_item_map'); } And in the Tag model I have public function category() { return $this->belongsToMany('Item', 'tag_item_map'); }
It works for me. You probably have something else going on. It is hard to tell without seeing the models.

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.