2016-11-25 66 views
1

我有一個Yii2 searchQuery設置,它非常適合計算那些不在給定點所需半徑內的記錄。使用Yii2查詢從函數中返回一個具有函數的值select

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` 

獲得的記錄喋喋不休的半徑計算,但是我需要的地理函數計算以及距離。我曾嘗試使用as關鍵字,但它始終打破查詢。

+0

查詢結果查詢回聲Yii :: $ app-> db-> createCommand($ query) - > sql – scaisEdge

+0

該查詢工作得很好......結果SQL語句是:SELECT DISTINCT * FROM'trainer' WHERE'性別'='0'HAVING ST_Distance_Sphere(POINT(-123.3836214,48.418248899999995),PointFromText(CONCAT('POINT(',longitude,'',latitude,')')))<59000 LIMIT 2 我需要得到結果距離回到控制器不知何故,我不知道鋤頭 –

+0

顯示代碼在哪裏你建立和執行查詢(但uodate的問題..否則真的很難讀代碼..) – scaisEdge

回答

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() 
     { 
     .... 

第二,你可以使用距離作爲你的意見模型屬性eg:gridview

<?= GridView::widget([ 
    'dataProvider' => $dataProvider, 
    ...... 
    'columns' => [ 
     ..... 
     'distance', 
     ... 
相關問題