samedi 19 août 2017

Adding a popular scope that counts unique values and orders them

Not quite sure how to word the title but essentially I am looking to create a scope that looks at my polymorphic relation (visitorable) and counts unique rows (based on ip address). I want to be able to call $this->profile->popular(3) in my controller and get a nice ordered list (3 being a limit and ordered by unique visitor numbers).

If there is no relation, I need to return 0 as the count so that I still get results if the entity has had no visits.

Here is what I have at the moment, but I am completely stuck on how I should go about this.

  public function visitors()
    {
        return $this->morphMany('SoundTrackIt\Visitor', 'visitorable');
    }

    public function scopePopular($query)
        {
            $query->whereHas('visitors', function($q) {
                $q->groupBy('ip_address');
            })->withCount('visitors');

            return $query;
        }



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2wknWXk
via IFTTT

Aucun commentaire:

Enregistrer un commentaire