0
// table: rates
+ -- + ------------ + -------------- + ----- + ----------- +
| id | ratable_id | rateble_type | score | create_at |userid
+ -- + ------------ + -------------- + ----- + ----------- +
| 1  | 1            | Events           | 4   | 2020-10-06  |3
| 2  | 1            | Events           | 4   | 2020-10-06  |2 
| 3  | 2            | Events           | 0   | 2020-10-06  |1
+ -- + ------------ + -------------- + ----- + ----------- +

// table: events
+ -- + ------------ + -------------- +
| id | name | rate  | create_at |
+ -- + ------------ + -------------- +
| 1  | eventd    | 4   | 2020-10-06  |
| 2  | evente    | 4   | 2020-10-06  |
| 3  | eventn    | 0   | 2020-10-06  |
+ -- + ------------ + -------------- +

code

public function rating()
    {
        return $this->morphMany(Rate::class, 'ratable');
    }  

$data = Event::with(['user'])
          ->with('rating')
          ->whereMonth('created_at', $month)
          ->orderBy('finalrate', 'desc')
          ->take(5)
          ->get()
          ->toArray();

Question: Using Laravel Eloquent morph relationship, how do I order a query by a column on a has morphMany polymorphic relationship? In the code above I will retrieve all the events details with the rating details and order by rate score. How can I orderby the higher rate and also the total rates table rows (mostly people vote in the event), does it mean that the sequence of the event will be based on a higher score and most people rate the event.

catch mela
  • 11
  • 3

1 Answers1

0

You can try some code here:

Order a query by a column on a has morphMany polymorphic relationship?

public function rating()
    {
        return $this->morphMany(Rate::class, 'ratable');
    }  

$data = Event::with(['user'])
          ->with('rating')
          ->whereMonth('created_at', $month)
          ->orderBy('rating.score', 'desc')
          ->take(5)
          ->get()
          ->toArray();

Orderby the higher rate and also the total rates table rows (mostly people vote in the event), does it mean that the sequence of the event will be based on a higher score and most people rate the event:

public function rating()
    {
        return $this->morphMany(Rate::class, 'ratable');
    }  

$data = Event::with(['user'])
          ->with('rating')
          ->whereMonth('created_at', $month)
          ->orderBy('SUM(rating.score)', 'desc')
          ->get()
          ->toArray();

Read more here: Laravel order results by column on polymorphic table and OrderBy Sum in Laravel

Ngô Minh
  • 117
  • 6