0

I've got following query which beats the crap out of my database, because it makes a a single query for every relation:

$projects = $this->project->all()->sortBy(function ($item) {
  return $item->votes()->count();
  }, SORT_REGULAR, true)->take(30);

I tried many different ways:

$projects = $this->project->with('Vote')->all()->sortBy(...)->take(30); Call to undefined method Illuminate\Database\Query\Builder::all()

$projects = $this->project->with('Vote')->get()->sortBy(...)->take(30); Call to undefined method Illuminate\Database\Query\Builder::Vote()

...

In the template I'm looping over the projects and use $project->votes()->count()

What is the correct way to do the eager loading?

Bernd Strehl
  • 2,852
  • 4
  • 24
  • 43

1 Answers1

0

I think the problem might be the all() in the middle. Try getting rid of the all() and adding get() at the end. Furthermore, you can use e.g. Project:: to make an Eloquent query, if you don't want to call an instance.

$projects = Project::with('vote')->sortBy(...)->take(30)->get();

That should solve it, I think. If you don't need any other project data, but rather the votes, than you might also be able to do a groupBy instead of looping through everything and then doing a count().

Oliver Adria
  • 1,123
  • 11
  • 23
  • 1
    This gives me `Call to undefined method Illuminate\Database\Query\Builder::sortBy()` – Bernd Strehl Mar 27 '14 at 08:45
  • Using `Project::` instead of `$this->project`, does that work? Did you make sure you have created a `Project` model which extends Eloquent? – Oliver Adria Mar 27 '14 at 08:56
  • I have different Project Models this is why i get my Project Model like this `public function __construct(){ $this->project = App::make('Project'); }` Works fine for all other purposes, can't say if this is the problem. – Bernd Strehl Mar 27 '14 at 09:58
  • But what does `$projects = Project::with('vote')->sortBy(...)->take(30)->get();` output with `get()` only at the end? – Oliver Adria Mar 27 '14 at 10:46
  • 1
    Nothing because I get this error: `Call to undefined method Illuminate\Database\Query\Builder::sortBy()` – Bernd Strehl Mar 28 '14 at 09:55
  • Try orderBy instead of sortBy. sortBy must be use on a collection object. – Needpoule Mar 28 '14 at 11:21