CakePHP 3.5始终将asText()MySQL函数应用于空间字段 [英] CakePHP 3.5 Always apply asText() MySQL function to Spatial field

查看:135
本文介绍了CakePHP 3.5始终将asText()MySQL函数应用于空间字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的PolygonType,它代表MySQL表中的POLYGON()字段.

I have a custom PolygonType which represents a POLYGON() field in a MySQL table.

class PolygonType extends BaseType implements ExpressionTypeInterface
{
    public function toPHP($value, Driver $d)
    {
        // $value is binary, requires unpack()
    }
}

我可以在每个 查找上使用$query->func()->astext(),但是我想知道是否有可能在选择此字段时始终应用MySQL的AsText()函数(类似于在插入数据时如何使用toExpression().

I can use $query->func()->astext() on every find, but I would like to know if it's possible to always apply MySQL's AsText() function when selecting this field instead (similar to how toExpression() can be used when inserting data).

推荐答案

基于 ndp

Based on ndp's answer, it's possible to inspect the field types via $query->getDefaultTypes() and apply a SQL function as required. However, $value is empty if no fields are initially stated (e.g. when using Table::get() so there's also a check for this.

public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
{
    $query->traverse(
        function (&$value) use ($query) {

            if (is_array($value) && empty($value)) {
                $query->all();
            }

            $defaultTypes = $query->getDefaultTypes();

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

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

这篇关于CakePHP 3.5始终将asText()MySQL函数应用于空间字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆