我有这个班级
<?php
namespace App\Models\Tables;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
class ZipCode extends Model
{
protected $table = 'zip';
public $timestamps = false;
protected $fillable = [
'latitude',
'longitude',
];
public static function radiusSearch($lat, $lng)
{
$circle_radius = 3959;
$subQuery = '(SELECT *, (' . $circle_radius . ' * acos(cos(radians(' . $lat . ')) * cos(radians(latitude)) * cos(radians(longitude) - radians(' . $lng . ')) + sin(radians(' . $lat . ')) * sin(radians(latitude)))) AS distance FROM zip) AS distances';
$result = ZipCode::select('*')
->from(ZipCode::raw($subQuery))
->limit(20);
var_dump($result);
return $result;
}
}
当我致电radiusSearch(...)
时,我得到一个Illuminate\Database\Eloquent\Builder
对象,而不是实际结果
$result->get()
不起作用,我得到Object of class Illuminate\Database\Eloquent\Builder could not be converted to string
这个通用查询工作得很好ZipCode::where('zip', '11111')->get()
而不是上面的
有什么想法吗?
编辑:$result
返回如下内容:
object(Illuminate\Database\Eloquent\Builder)[170]
protected 'query' =>
object(Illuminate\Database\Query\Builder)[164]
public 'connection' =>
object(Illuminate\Database\MySqlConnection)[166]
protected 'pdo' =>
object(PDO)[175]
...
protected 'model' =>
object(App\Models\Tables\ZipCode)[171]
protected 'table' => string 'zip' (length=9)
public 'timestamps' => boolean false
...
如果我$result->getModel()->get()->toArray()
,则返回表格中的所有结果
答案 0 :(得分:1)
您已经看过代码
$result = ZipCode::select('*')
->from(ZipCode::raw($subQuery))
->limit(20);
将返回代表您查询的Builder对象。您需要调用 - &gt; get()让构建器实际执行您的查询并返回结果
$result = ZipCode::select('*')
->from(ZipCode::raw($subQuery))
->limit(20)->get();
答案 1 :(得分:0)
以下是我根据其他社区答案提出的解决方案
public static function getClosestCities($lat, $lng, $city, $distance = 20, $limit = 20)
{
$coordinates = ['latitude' => $lat, 'longitude' => $lng];
$cares = self::scopeIsWithinMaxDistance(ZipCode::raw('select *'), $coordinates, $distance, $city)->limit($limit)->get();
return $cares ? $cares->toArray() : null;
}
public static function scopeIsWithinMaxDistance($query, $coordinates, $radius = 5, $city)
{
$haversine = "(3961 * acos(cos(radians(" . $coordinates['latitude'] . "))
* cos(radians(`latitude`))
* cos(radians(`longitude`)
- radians(" . $coordinates['longitude'] . "))
+ sin(radians(" . $coordinates['latitude'] . "))
* sin(radians(`latitude`))))";
return $query->select('*')
->selectRaw("{$haversine} AS distance")
->orderByRaw("{$haversine} asc")
->whereRaw("{$haversine} < ?", [$radius])
->groupBy("city");
}