Laravel 5 Eloquent - 将计算值添加为集合的列

时间:2018-03-29 13:33:02

标签: laravel laravel-5 eloquent

我正在计算老师和学校的距离。

我正在查询用户表,然后使用whereHas()查询userable_type教师。教师表具有经度和纬度值。

当我直接查询教师模型而不是首先查询用户模型时,以下内容对我有用了!

        $query = User::where('userable_type', 'App\Teacher');

        $query->with('userable');

        if($school->latitude == '' || $school->longitude == '') {

          \Session::flash('warning', 'Please check your school profile postcode; it appears that the system was unable to geocode your postcode! Results shown do not reflect any distances of staff from your school!');

        } else {

            $query->whereHas('teacher', function ($query) use ($school) {

                $haversine = "(3961 * acos(cos(radians($school->latitude)) 
                    * cos(radians(latitude)) 
                    * cos(radians(longitude) 
                    - radians($school->longitude)) 
                    + sin(radians($school->latitude)) 
                    * sin(radians(latitude))))";

                $query->select() //pick the columns you want here.
                    ->selectRaw("{$haversine} AS distance")
                    ->whereRaw("{$haversine} < ?", '20');
                    // ->havingRaw('{$haversine}', '<', '20');

            });

        }

        $query->whereDoesntHave('thisSchool');

        $teachers = $query->get();

未创建“距离”字段但不会引发任何错误!所以我的问题是,在这种情况下,如何按照我想要的距离为每个用户添加“距离”值?

这是直接查询教师模型的查询,它可以正常工作!

     $query = Teacher::with('user', 'user.schools', 'criterias', 'criterias.stafftype', 'criterias.teachingstage', 'criterias.teachingsubject')
            ->where('public', 1)
            ->where('verified', 1);

            if($school->latitude == '' || $school->longitude == '') {

              \Session::flash('warning', 'Please check your school profile postcode; it appears that the system was unable to geocode your postcode! Results shown do not reflect any distances of staff from your school!');

            } else {

              if( $filters['distance'] != '' ) {

                  $haversine = "(3961 * acos(cos(radians($school->latitude)) 
                       * cos(radians(latitude)) 
                       * cos(radians(longitude) 
                       - radians($school->longitude)) 
                       + sin(radians($school->latitude)) 
                       * sin(radians(latitude))))";

                  $query->select() //pick the columns you want here.
                      ->selectRaw("{$haversine} AS distance")
                      ->whereRaw("{$haversine} < ?", [$filters['distance']]);

              }

            }

            $query->orderBy( 'active', 'DESC' );
            $query->orderBy( 'distance', 'ASC' );

            $teachers = $query->paginate( $filters['perpage'] );

谢谢, ķ...

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决这个问题的方法,可以在这里找到:

Laravel 5 eloquent - add child field to parent model