CakePHP 3-默认情况下,在表对象中的select()中使用SQL函数

问题描述 投票:0回答:1

我正在为具有某些POINT列的数据库建立系统。我使用了食谱示例来构建自定义类型,并且它似乎正在工作。但是,要处理POINT,我需要以特殊的方式SELECT

SELECT ST_AsText(location) as location ...

对于查询构建器来说,这并不难:

$this->Houses->find()->select(['location' => 'ST_AsText(location)'])

但是,我希望默认情况下会发生这种情况。

我曾考虑使用beforeFind事件,但找不到以下伪代码的正确函数:

public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
{
    if 'location' in query->getSelectedFields():
         replace 'location' by 'location' => 'ST_AsText(location)'
}

[将要包含在字段中的字段如何替换为一个函数?理想情况下,即使我尚未从控制器调用->select(...)

关于CakePHP讨论的较旧的类似问题: https://discourse.cakephp.org/t/read-data-from-spatial-mysql-field-point-polygon/2124

cakephp orm model cakephp-3.0
1个回答
0
投票

CakePHP 3.5 Always apply asText() MySQL function to Spatial field中找到了我的解决方案。

这对于CakePHP 3.8很好。我决定将事件处理放到一个行为中,以使其易于重用:

<?php
// src/Model/Behavior/SpatialBehavior.php    

namespace App\Model\Behavior;

use Cake\ORM\Behavior;
use Cake\ORM\Table;
use Cake\Event\Event;
use ArrayObject;
use Cake\ORM\Query;

/**
 * Spatial behavior
 * 
 * Make sure spatial columns are loaded as text when needed.
 * 
 * @property \Cake\ORM\Table $_table
 */
class SpatialBehavior extends Behavior
{

    /**
     * Default configuration.
     *
     * @var array
     */
    protected $_defaultConfig = [];

    /**
     * Callback before each find is executed
     * 
     * @param Event $event
     * @param Query $query
     * @param ArrayObject $options
     * @param type $primary
     */
    public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
    {
        $query->traverse(function (&$value) use ($query)
        {
            if (is_array($value) && empty($value))
            {
                // Built up standard query when ->select() was never used
                //$query->all(); // Execute query to learn columns
                $query->select($this->_table);
            }

            $defaultTypes = $query->getDefaultTypes();

            foreach ($value as $key => $field)
            {
                if (in_array($defaultTypes[$field], ['point', 'polygon']))
                {
                    $value[$key] = $query->func()->ST_AsText([
                        $this->_table->aliasField($field) => 'identifier'
                    ]);
                }
            }

            $query->select($value);
        }, ['select']);
    }

}

在我的表格对象中:

class HousesTable extends Table
{
    public function initialize(array $config)
    {
        //...
        $this->addBehavior('Spatial');
        //...
    }
© www.soinside.com 2019 - 2024. All rights reserved.