访问虚拟字段中的多个外部字段?

时间:2014-01-30 17:48:08

标签: php mysql cakephp foreign-keys cakephp-2.4

两个表,在Cakephp中正确设置了关系:

属性(..., postcode_id ,...)和邮政编码( id ,邮政编码,纬度,经度)。

在Property beforeFind()中创建的虚拟字段计算搜索邮政编码和记录邮政编码之间的距离。因此,要获得lat / long,我需要通过Property记录中的外键从Postcode表中检索记录,所有这些都在虚拟字段声明中。

我该怎么做?多个SELECT嵌套在?嵌套的find(),可能会更糟?我认为只使用RelatedModel.fieldName就可以了 - 它没有。

编辑:属性属于邮政编码,邮政编码有很多属性

(使用cakephp v2.4.4)

属性beforeFind()中的虚拟字段:

$this->virtualFields['distance'] = 6371 . ' * ACOS(
    (SIN(RADIANS(Postcode.latitude)) * ' . $searchPostcode['latitudeSin'] . ') +
    (COS(RADIANS(Postcode.latitude)) * ' . $searchPostcode['latitudeCos'] . ') *
     COS(RADIANS(Postcode.longitude) - ' . $searchPostcode['longitude'] . ')
)';

2 个答案:

答案 0 :(得分:0)

你需要在你正在搜索的表和保存lng / lat的表之间进行手动连接,例如,$ options ['join'] = array(array('table'=> 'model2','alias'=>'Model2','conditions'=> array('Model2.model1_id = Model1.id')));然后在你的虚拟领域,我认为你应该能够使用Model2.lat和Model2.lng并让它工作。

答案 1 :(得分:0)

我有它工作,但我不得不在每个外部调用中嵌套另一个SELECT,这不是最好的解决方案。例如,

RADIANS((SELECT latitude FROM postcodes WHERE id = Property.postcode_id))

这也意味着相同的值,纬度,被检索两次,所以这不是很好。

如果您有一个更好的解决方案,请分享!