2

I have 2 collections. Vehicles and Views. I would like to bring back a list of vehicles sorted by the number of views.

My Vehicle class

class Vehicle extends Moloquent {

    protected $dates = ['date_assigned'];

    public function associated_views()
    {
        return $this->hasMany('App\Collections\View');
    }

}

And my View class

class View extends Moloquent {

    public function associated_vehicle()
    {
        return $this->belongsTo('App\Collections\Vehicle');
    }

}

I can get the count of the views after the fact, with $vehicle->associated_views->count(), but this doesn't enable me to sort on the field before pulling back every single record. Is this possible?

JBxOnline
  • 1,339
  • 1
  • 9
  • 10
  • see if this post can help you! https://stackoverflow.com/questions/18861186/eloquent-eager-load-order-by or https://stackoverflow.com/questions/25700529/laravel-eloquent-how-to-order-results-of-related-models – LorenzoBerti Oct 16 '17 at 15:20
  • @LorenzoBerti, yeah, I've read that through a number of times, but I'm not sure I can orderby an aggregate (i.e. Count). I'll try a few more ideas, but not getting it working yet... – JBxOnline Oct 16 '17 at 15:25

1 Answers1

0

Use withCount():

Vehicle::withCount('views')->latest('views_count')->get()

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models

https://laravel.com/docs/5.5/eloquent-relationships#counting-related-models

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • This _should_ be the perfect answer... However, I get an error and it looks to me like it's a bug in laravel-mongodb: https://github.com/jenssegers/laravel-mongodb/issues/1147 – JBxOnline Oct 17 '17 at 08:19
  • @JBxOnline the problem is you're working with DB through a package (which is always a bad idea). So, instead of using Laravel functionality you need to ask the package author about a workaround for this. – Alexey Mezenin Oct 17 '17 at 08:22
  • I disagree that it is always a bad idea to use a package. Eloquent is essentially a package. You should also note that I tagged my question with jenssegers-mongodb to make it clear that I'm working with a Mongo database via this package. Regardless, withCount should still work and I have already raised the issue with the package author. And seeing as your suggestion should provide exactly the functionality I'm after, I've marked it as the best answer. I wasn't previously aware of the withCount() method. – JBxOnline Oct 17 '17 at 08:30