自动 select 特定 hstore 与 pomm 项目

Automatically select specific hstore with pomm project

我想要 select 轻松地使用特定的 hstore 键多行。这里是 "fr" 键。 可以看到如下结构:

+----+----------------+-------------------------+
| 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"  |
+----+----------------+-------------------------+

我想用 Pomm Project. For that I create a extendable ModelI18n for that. You can see here 获得这个结果。

覆盖默认投影是个好习惯吗?你有别的想法吗?

据我了解,您想使用 HStore 字段保存翻译。

模型 classes 通过投影与 PHP 实体建立 link 数据库关系,因此投影意味着过载。

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

此投影将使常规查询类似于

$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

您可以使用完全相同的方式使用 JSONB 字段。

您提供的createProjection方法比较通用,可以在GenericModelclass中被其他模型扩展。