2

I want select easily multiple row with a specific hstore key. Here "fr" key. You can see the follow structure:

+----+----------------+-------------------------+
| id | name_i18n      | description_i18n        |
+----+----------------+-------------------------+
|  1 | "fr"=> "nom 1" | "fr"=> "Description 1"  |
+----+----------------+-------------------------+
|  2 | "fr"=> "nom 2" | "fr"=> "Description 2"  |
+----+----------------+-------------------------+
|  3 | "fr"=> "nom 3" | "fr"=> "Description 3"  |
+----+----------------+-------------------------+

I want to obtain this result with Pomm Project. For that I create a extendable ModelI18n for that. You can see here.

It is a good practice to override the default projection? Do you have a other idea ?

1 Answers1

0

From what I understand, you want to save translations using a HStore field.

Model classes do link database relations to PHP entities through a projection so the projection is meant to be overloaded.

<?php

class MyEntityModel extends Model
{
    protected $culture = 'en';

    public function setCulture($culture)
    {
        $this->culture = $culture;

        return $this;
    }

    public function createProjection()
    {
        return parent::createProjection()
            ->unsetField('name_i18n')
            ->setField(
                'name',
                sprintf("%%:name_i18n:%%->'%s'", $this->culture),
                'varchar'
            )
            ->unsetField('description_i18n')
            ->setField(
                'description',
                sprintf("%%:description_i18n:%%->'%s'", $this->culture),
                'text'
            )
        ;
    }
}

This projection will make regular queries to be like

$entity = $pomm
    ->getDefaultSession()
    ->getModel(MyEntityModel::class)
    ->setCulture('fr')
    ->findByPk(['id' => $id])
    ;
/*
    SELECT
      id as id,
      name_i18n->'fr' as name,
      description_i18n->'fr' as description
    FROM
      a_schema.a_table
    WHERE
      id = $*
*/

echo $entity['name']; // nom 1
echo $entity['description']; // Description 1

You can use a JSONB field exactly the same way.

The createProjection method you provide is more generic, it can be in a GenericModel class extended by other models.

greg
  • 3,354
  • 1
  • 24
  • 35