laravel 查询构造器-闭包

在写计算地理位置距离时,用到了数据库闭包扩展

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// gps距离计算
$gpsSQL = "ROUND(ROUND(ST_Distance_Sphere"
. "(point({$gpsData->lng},{$gpsData->lat}),"
. "point(x({$rawTable}.point),y({$rawTable}.point)))) / 1000,2)";
$selSQL = $gpsSQL . " as hosp_rang ,"
. " {$rawTable}.hosp_name, {$rawTable}.id,"
. "{$rawTable}.city_id, {$rawTable}.province_id ";

// 搜索医院名称则是全局搜索不含距离
$rangWhere = " 1 ";
if (empty($gpsData->hosp_name)) {
$rangWhere = $gpsSQL . '<=' . $gpsData->rang;
}
$rangHosp = DB::table($this->table)
->select(DB::raw($selSQL))
->whereRaw($rangWhere)
->orderBy($this->table . '.id')
->toSql();

// 汇总计算,在where条件中用到闭包的方式,匿名函数中用use从外部引入变量
$hospData = DB::table(DB::raw("({$rangHosp}) as ranghosp"))
->where(function ($query) use ($gpsData) {
$rawSql = " hosp_rang IS NOT NULL ";
if (isset($gpsData->hosp_name) &&
!empty($gpsData->hosp_name)
) {
$rawSql .= " && ranghosp.hosp_name like '%{$gpsData->hosp_name}%'";

}
$rawSql .= " && 1 ";
$query->whereRaw($rawSql);
})
->orderBy("hosp_rang")
->limit($limit)
->get();

这里where部分使用了匿名函数,可以多个where的中都使用闭包方式。同时用$query作为参数引入,使得用查询本身又使用了一个子查询。

DB::raw() 使用纯sql语句结构