Multi language database, with default fallback

后端 未结 2 705
春和景丽
春和景丽 2021-01-29 19:47

I have a question that, I know, has been widely discussed about, but in my opinion, there is one aspect that still needs clarification.

I am creating a web-application w

2条回答
  •  面向向阳花
    2021-01-29 20:35

    Using common shared table for all translatable fields of all tables

    In the above approach the translation table is an extension of the parent table. Hence ProductTranslation has all the translatable fields of Product. It is a neat and quick approach and nice one as well.

    But there is one disadvantage (not sure if it can be called disadvantage). If many more tables require translate-able fields, that many new tables are required. From my experience we took a different approach. We created a generic table for translation and a link table to link translations to the translate-able fields of the parent table.

    So I'm going to use the previous example of Product which has two fields title and description that are translate-able to explain our approach. Also consider another table ProductCategory with fields name and description that also require translations.

    Product
    (
       ID: Integer
       SKU: String
       titleID: Integer // ID of LocalizableText record corresponding title
       descriptionID: Integer // ID of LocalizableText record corresponding description
    )
    
    ProductCategory
    (
       ID: Integer
       nameID: Integer // ID of LocalizableText record corresponding name
       descriptionID: Integer // ID of LocalizableText record corresponding description
    )
    
    LocalizableText // This is nothing but a link table
    {
        ID: Integer
    }
    
    Translations //This is where all translations are stored.
    {
        ID: Integer
        localizableTextID: Integer
        language: String
        text: String
    }
    

    To load this data, I'm using different queries (modified the above). E.g. to load a product with ID @Id in the language @Language, I'd use the following query

    SELECT
        p.ID,
        p.SKU,
        -- get title, description from the requested translation,
        -- or fall back to the default if not found:
        Title.text Title,
        description.text Description
      FROM Products p
      -- join requested translation for title, if available:
      LEFT OUTER JOIN Translations title
        ON p.titleID = title.localizableTextID
           AND title.Language = @Language
      -- join requested translation for description, if available:
      LEFT OUTER JOIN Translations description
        ON p.descriptionID = description.localizableTextID
           AND description.Language = @Language
      WHERE p.ID = @Id
    

    This query is based on the assumption that individual fields of Product does not have a default translation

    Similar query can be used to fetch records from ProductCategory

提交回复
热议问题