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  |
+ -- + ------------ + -------------- +

代码

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();

问题:使用 Laravel Eloquent 变形关系,我如何通过具有 morphMany 多态关系的列对查询进行排序?在上面的代码中,我将检索所有带有评分详细信息的事件详细信息,并按评分排序。我如何较高的费率和总费率表行排序(主要是人们在事件中投票),这是否意味着事件的顺序将基于更高的分数并且大多数人对事件进行评分

4

1 回答 1

0

你可以在这里尝试一些代码:

按具有 morphMany 多态关系的列排序查询?

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();

按较高的比率排序以及总比率表行(主要是人们在事件中投票),这是否意味着事件的顺序将基于更高的分数并且大多数人对事件进行评分:

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();

在此处阅读更多内容:Laravel 按多态表上的列排序结果Laravel 中的 OrderBy Sum

于 2020-10-28T10:06:22.487 回答