【问题标题】:Automatically select specific hstore with pomm project使用 pomm 项目自动选择特定的 hstore
【发布时间】:2015-09-06 03:06:59
【问题描述】:

我想使用特定的 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 获得这个结果。为此,我为此创建了一个可扩展的 ModelI18n。你可以看到here

覆盖默认投影是一种好习惯吗?你有其他想法吗?

【问题讨论】:

    标签: php postgresql pomm


    【解决方案1】:

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

    模型类确实通过投影将数据库关系链接到 PHP 实体,因此投影意味着重载。

    <?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 方法更通用,可以在其他模型扩展的GenericModel 类中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2011-04-13
      • 2020-01-31
      相关资源
      最近更新 更多