Sunday, January 9, 2022

[FIXED] CakePHP 3.5 Always apply asText() MySQL function to Spatial field

Issue

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()
    }
}

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


Solution

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']
    );
}


Answered By - robmcvey

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.