Database agnostic virtual fields in CakePHP

CakePHP 1.3 has a feature for virtual fields , but in combination with the database you are using. For instance:

var $virtualFields = array(
  'full_name' => 'CONCAT(User.first_name, " ", User.last_name)'
);

This will work for MySQL, but not for MS SqlServer. Is there a way to make this database agnostic?

I am still in the middle of application development and still don’t know which database we will use in production. Therefore, I want access to the database to be as agnostic as possible.

+3
source share
1 answer

You can measure your property Model::virtualFieldsso that it has rules for each database:

var $virtualFields = array(
    'mysql' => array(
        'display_name' => 'CONCAT(User.name, " (", User.team, ")")',
    ),
    'postgres' => array(
        'display_name' => 'PgConcatStuff(...)',
    ),
    'mssql' => array(
        'display_name' => 'MsConcatStuff(...)',
    ),
);

, , Cake :

class AppModel extends Model {

    function beforeFind($queryData) {
        $ds = $this->getDataSource();
        $db = $ds->config['driver'];
        $this->virtualFields = $this->virtualFields[$db];
        return parent::beforeFind($queryData);
    }

. , , . .:)

+2

Source: https://habr.com/ru/post/1744352/


All Articles