在数据库查询中按从高到低排列顺序



1.我对如何在年龄的数据库查询中添加排序顺序(从高到低)感到困惑。我已经尝试了一些代码,但它产生了一个错误。非常感谢这里的任何帮助。

public function ListOrgaScholar($ship_id){
        $ship = Scholarship::find($ship_id);
        $ship_age_from = $ship->ship_age_from;
        $ship_age_to = $ship->ship_age_to;
        $scholars = (new Scholar)->newQuery()->select('*');
        $scholars->whereBetween(DB::raw('TIMESTAMPDIFF(YEAR,scholars.scholar_birthday,CURDATE())'),array($ship_age_from,$ship_age_to)); 
        $scholars = $scholars->get();
}

2.这里也一样。如何添加 orderby(从最高到最低),因为它是两个不同的 where 子句。$ship_gpa_from$ship_gpa_to是等级的输入。

    public function ListOrgaScholar($ship_id){
           $ship = Scholarship::find($ship_id);
           $ship_gpa_from = $ship->ship_gpa_from;
           $ship_gpa_to = $ship->ship_gpa_to;
           $scholars = (new Scholar)->newQuery()->select('*');
          if($ship_gpa_from)
            $scholars->where('scholar_GPA', '>=', $ship_gpa_from);
          if($ship_gpa_to)
            $scholars->where('scholar_GPA', '<=', $ship_gpa_to);
    $scholars = $scholars->get();
}

您是否尝试过将结果作为集合返回,然后对其应用集合函数?代码看起来有点像这样:

$scholarship = Scholarship::find($id);
$scholars = Scholar::all();
$selectedScholars  = $scholars->filter(function ($item, $key) {
    $scholarAge = Carbon::now() - $item->scholar_birthday //this depends on the value of scholar_birthday;
    return ($scholarAge >= $scholarship->ship_age_from &&  $scholarAge <= $scholarship->ship_age_from);
})->sortBy("scholar_birthday");

最新更新