1

I have a quick and straightforward question. Which of the following queries is preferred while working with Eloquent ORM in Laravel?

$post = Post::with(array('user', 'comments.from'))->find($id);
$post = Post::with(array('user', 'comments.from'))->where('postID', $id)->get();

I'm struggling to find the difference between ->find and ->get with eager loading.

postID is my primary key in the posts table above. Both performance are nearly identical via my debugger and each run 8 queries.

If anyone can shed some light on this, I'd really appreciate it.

1 Answer 1

4
  1. This is what you should use; it will return one result model:

    $post = Post::with(array('user', 'comments.from'))->find($id);
    
  2. This will return a collection of results (even if there's only one):

    $post = Post::with(array('user', 'comments.from'))->where('postID', $id)->get();
    
  3. Instead of method 2, what you probably mean to do is this:

    $post = Post::with(array('user', 'comments.from'))->where('postID', $id)->first();
    

Methods 1 and 3 will basically get you the exact same result. Method 1 is more adaptable because it'll continue to work if you change the primary key for the table. It's also faster than the other two methods because it doesn't construct a collection of models.

By the way,this has nothing to do with the eager-loading, as these functions will all work the same on any query.

4
  • Is this even considered eager loading? Feb 23, 2014 at 0:26
  • @user1011713 barely lol. with() and load() are for eager-loading in Laravel, but in this instance, you're just using them to load additional information into your model. If you were actually getting a collection of models, such as Post::with('comments')->get() to get all of your posts with their comments, it would be considered eager-loading because you're retrieving all of the data with just 2 queries, as opposed to n + 1 queries.
    – TonyArra
    Feb 23, 2014 at 0:30
  • Any ideas how I could eager load the relationship? Feb 23, 2014 at 0:34
  • @user1011713 it's irrelevant unless you're working with multiple posts. Otherwise, you'd do something like the Book method here laravel.com/docs/eloquent#eager-loading
    – TonyArra
    Feb 23, 2014 at 0:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.