开发者

Retrieving i18n data with fallback language

开发者 https://www.devze.com 2023-01-07 16:09 出处:网络
I have to grab i18n text from a database. The default language is English, it has text for everything. But the non-English languages doesn\'t necessarily have all the desired translations. If a non-En

I have to grab i18n text from a database. The default language is English, it has text for everything. But the non-English languages doesn't necessarily have all the desired translations. If a non-English translation for a certain entity/key isn't available in the DB, then I'd like to have it to return the English text instead. So, English is the fallback language here.

The i18n text table look like so (PostgreSQL dialect):

CREATE TABLE translation (
    id SERIAL PRIMARY KEY,
    language_code CHAR(2) NOT NULL,
    key VARCHAR(20) NOT NULL,
    value TEXT NOT NULL,
    CONSTRAINT translation_unique UNIQUE (language_code, key)
)

The data look like this:

INSERT INTO translation 
    (language_code, key, value) 
VALUES
    ('en', 'foo', 'foo in English'),
    ('nl', 'foo', 'foo in Nederlands (Dutch)'),
    ('en', 'bar', 'bar in English')

I'd like to basically do the below pseudo SQL query:

SELECT key, value 
FROM translation 
WHERE (language_code = 'nl' OR IF value IS NULL THEN language_code = 'en')

(actually, the 'nl' value is to be parameterized)

So that it returns the following:

+-----+---------------------------+
| key | value                     |
+-----+---------------------------+
| foo | foo in Nederlands (Dutch) |
| bar | bar in English            |
+-----+---------------------------+

How can I ach开发者_如何学运维ieve this in a single SQL query?

The DB in question is PostgreSQL, but a RDMBS-agnostic way would be nice.


try something like this:

SELECT
    e.key,COALESCE(o.value,e.value)
    FROM Translation                e
        LEFT OUTER JOIN Translation o ON e.key=o.key and o.language_code='nl'
    WHERE e.language_code='en'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号