Note that there are some explanatory texts on larger screens.

plurals
  1. PORetrieving i18n data with fallback language
    primarykey
    data
    text
    <p>I have to grab i18n text from a database. The default language is English, it has text for <em>everything</em>. 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 <em>fallback</em> language here.</p> <p>The i18n text table look like so (PostgreSQL dialect):</p> <pre><code>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) ) </code></pre> <p>The data look like this:</p> <pre><code>INSERT INTO translation (language_code, key, value) VALUES ('en', 'foo', 'foo in English'), ('nl', 'foo', 'foo in Nederlands (Dutch)'), ('en', 'bar', 'bar in English') </code></pre> <p>I'd like to basically do the below pseudo SQL query:</p> <pre><code>SELECT key, value FROM translation WHERE (language_code = 'nl' OR IF value IS NULL THEN language_code = 'en') </code></pre> <p><em>(actually, the <code>'nl'</code> value is to be parameterized)</em></p> <p>So that it returns the following:</p> <pre> +-----+---------------------------+ | key | value | +-----+---------------------------+ | foo | foo in Nederlands (Dutch) | | bar | bar in English | +-----+---------------------------+ </pre> <p>How can I achieve this in a single SQL query?</p> <p>The DB in question is PostgreSQL, but a RDMBS-agnostic way would be nice.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload