Laravel查询生成器 - 使用特殊数据类型查询

时间:2016-03-19 03:17:58

标签: php mysql laravel query-builder laravel-query-builder

我有一张这样的表 -

enter image description here

因此,POINT我有一个特殊的数据类型(user_location)。

RAW选择查询是这样的 -

SELECT
  id,
  full_name,
  website,
  X(user_location) AS "latitude",
  Y(user_location) AS "longitude",
  (
    GLength(
      LineStringFromWKB(
        LineString(
          user_location, 
          GeomFromText('POINT(51.5177 -0.0968)')
        )
      )
    )
  )
  AS distance
FROM users
  ORDER BY distance ASC;

结果是 -

enter link description here

我想在Laravel with Query构建器中使用它,以便(51.5177 -0.0968)这两个点可以来自用户输入。

我所做的是 -

DB::table('users')
   ->select(
             id,
             full_name,
             website,
             DB::raw('X(user_location) AS "latitude"'),
             DB::raw('Y(user_location) AS "longitude"'),
             DB::raw('(
                        GLength(
                          LineStringFromWKB(
                            LineString(
                              user_location, 
                              GeomFromText('POINT(51.5177 -0.0968)')
                            )
                          )
                        )
                      )
                      AS distance')
             )
  ->orderBy('distance', 'asc')
  ->get();

但它没有用。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我认为你非常接近。试试这个:

DB::table('users')
    ->select(
        'id',
        'full_name',
        'website',
        DB::raw('X(user_location) as latitude'),
        DB::raw('Y(user_location) as longitude'),
        DB::raw('(
                GLength(
                  LineStringFromWKB(
                    LineString(
                      user_location,
                      GeomFromText(POINT(51.5177 - 0.0968))
                    )
                  )
                )
              )
              as distance')
    )
    ->where('status', '<>', 1)
    ->orderBy('distance', 'asc')
    ->get();