我有一个Yii2 searchQuery设置,非常适合计算不在给定点所需半径范围内的记录。
public function search($params)
{
$query = TrainerExtend::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => $this->pageSize,
],
]);
$this->load($params);
$query->having([
'<',
'ST_Distance_Sphere(POINT(' . $this->longitude . ',' . $this->latitude . '),
PointFromText(CONCAT(\'POINT(\',longitude,\'\',latitude,\')\')))',
$this->radius * 1000
]);
}
$rows = $query->distinct();
return $dataProvider;
}
public function actionFind()
{
$searchModel = new TrainerSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$trainers = $dataProvider->getModels();
if (array_key_exists('trainerSearch',Yii::$app->request->queryParams)
&& !empty($trainerSearch = Yii::$app->request->queryParams['TrainerSearch']))
{
if (array_key_exists('specialties',$trainerSearch) && !empty($specialities = $trainerSearch['specialties']))
{
foreach ($trainers as $trainer) {
$specialties = $trainer->trainerSpecialtiesArray;
$trainer->match = $this->caluclateRelevance($specialties);
}
}
}
return $this->render('find', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
结果查询
SELECT DISTINCT * FROM `trainer` WHERE `gender`='0' HAVING ST_Distance_Sphere(POINT(-123.3836214,48.418248899999995), PointFromText(CONCAT('POINT(',longitude,' ',latitude,')'))) < 59000 LIMIT 2`
结果记录是半径计算的结果,但我也需要geo函数计算的距离。我尝试过使用as关键字,但它一直在破坏查询。
答案 0 :(得分:2)
对于计算列,您必须在查询中添加正确的选择代码
$query->->addSelect(["*",
"ST_Distance_Sphere(POINT($this->longitude ,
$this->latitude ),
PointFromText(CONCAT('POINT(',longitude,' ',latitude,')')))as distance"]);
然后显示结果
首先,您应该在模型中添加公共变量,例如:
class TrainerExtend extends \yii\db\ActiveRecord
{
public $distance; // codice di stato del codice fiscale
......
public static function tableName()
{
....
第二,您可以在视图中使用距离作为模型属性,例如:gridview
<?= GridView::widget([
'dataProvider' => $dataProvider,
......
'columns' => [
.....
'distance',
...