No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Database

language_id and store_id in OpenCart: languages and stores in the database in 3.0 and 4.1

How OpenCart stores languages and stores in the database: the _description and _to_store tables, where config_language_id and config_store_id come from, and what a module should do.

11 min read OC 3.0 OC 4.1

language_id in OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → is the numeric identifier of a language. It is stored in the language table and appears in every table that holds translations (product_description, category_description, and so on). store_id likewise ties data to a store through the *_to_store and setting tables. At the start of each request, the core places the current values in config_language_id and config_store_id, and your module must use exactly those values in every query to these tables.

Below is how this works in OpenCart 3.0 and 4.1 (4.1.0.4), where the versions differ and where module developers most often make mistakes. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

Which tables contain language_id and store_id?

The schema is built on two simple patterns. The first is the description table. An entity (product, category, attributeA product characteristic that does not affect the price: material, weight, power. It is set in "Catalog → Attributes" and displayed on the "Specification" tab. More in the glossary →) has a main table with language-independent fields and a *_description table with a composite key of "entity id + language_id". For example, in product_description the primary key is (product_id, language_id), so each language has exactly one row with the name, description, and meta tags. The second is the store binding table: product_to_store, category_to_store, information_to_store, and manufacturer_to_store, keyed by "id + store_id". If a row exists, the entity is visible in the store; if no row exists, it is not visible.

For an overview of the core tables, see the article on the OpenCart database schema. Here we cover only what concerns languages and stores.

WhatOpenCart 3.0OpenCart 4.1
Language tablelanguage: language_id, name, code, locale, image, directory, sort_order, statuslanguage: language_id, name, code, locale, extension, sort_order, status
Store tablestore: store_id, name, url, sslstore: store_id, name, url
Language and store togetherseo_url (store_id, language_id, query, keyword), translation, customer_searchseo_url (store_id, language_id, key, value, keyword, sort_order), translation, customer_search, gdpr
Order snapshotorder.store_id, order.language_idorder.store_id, order.language_id, order.language_code
Customercustomer.store_id, customer.language_idsame

In 4.1 there are more language-related tables: country_description and zone_description were added, along with CMS article descriptions (article_description, topic_description). Note also that there is no store_id = 0 row in the store table. This is the main store, whose data comes from the settings and config. store holds only the additional stores.

How does the core determine the current language and store?

Both values are set in the startup controllers before the request reaches your code. So you don't need to calculate anything in your model: just use $this->config->get('config_language_id') and $this->config->get('config_store_id').

Store

The logic is the same in both branches. The core builds the address from HTTP_HOST (without www.) and the script directory, then looks for a match in the store table. If the GET contains store_id, that value is used; otherwise the matched store is used; otherwise 0. OpenCart 3.0 does this in catalog/controller/startup/startup.php and compares against the ssl or url column depending on HTTPS. OpenCart 4.1 does it in catalog/controller/startup/setting.php through model_setting_store->getStoreByHostname().

Language

OpenCart 3.0: the language code is checked in order: session, the language cookie, the Accept-Language header (first by the locale field, then by code), and if nothing matches, the config_language setting. The chosen code is written to the session and to a cookie for 30 days.

OpenCart 4.1: there is no session, cookie, or browser detection in catalog/controller/startup/language.php. The language comes from the language GET parameter, and if it is absent, from config_language_catalog. Therefore, in 4.1 store links carry language=uk-ua, and a module that builds URLs itself must preserve this parameter.

flowchart TD
  A["Request to catalog"] --> B["Find store by HTTP_HOST"]
  B --> C["config_store_id"]
  C --> D["Settings: store_id 0 + current"]
  D --> E["Determine language code"]
  E --> F["config_language_id from language table"]
  F --> G["Module controllers and models"]

In the admin area, config_language_id means the administrator's interface language. In 3.0 it is set by config_admin_language, and in 4.1 by config_language_admin. This matters later when we discuss copying descriptions. For how a module's language files are loaded for the selected language, see the separate article on OpenCart language files.

How to write a query with language_id and store_id correctly?

Look at how the 4.1 core fetches a product in catalog/model/catalog/product.php, method getProduct(): the query starts from product_to_store, then joins LEFT JOIN on product and product_description, and the WHERE clause contains both conditions, p2s.store_id = config_store_id and pd.language_id = config_language_id. OpenCart 3.0 does the same with a different table order. Your module should follow the same pattern.

Example

public function getItems(int $limit = 10): array {
	$sql = "SELECT p.product_id, pd.name, p.price
		FROM `" . DB_PREFIX . "product` p
		INNER JOIN `" . DB_PREFIX . "product_description` pd
			ON (pd.product_id = p.product_id AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "')
		INNER JOIN `" . DB_PREFIX . "product_to_store` p2s
			ON (p2s.product_id = p.product_id AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "')
		WHERE p.status = '1'
		ORDER BY p.sort_order, pd.name
		LIMIT " . (int)$limit;

	return $this->db->query($sql)->rows;
}

A few details that are easy to miss:

  • Put the language condition in the ON or WHERE clause, but always include it. Without it, the JOIN on *_description multiplies rows by the number of languages. In a store with three languages, the product list suddenly becomes three times longer, and COUNT(*) is wrong.
  • A LEFT JOIN with the condition in ON returns a product with an empty name if no translation exists. An INNER JOIN hides such a product. For the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary →, hiding is usually correct; for the admin, it is better to show and highlight it.
  • Cast to int. Config values are reliable, but the habit of casting (int) saves you when the id comes from GET.
  • Cache with both ids in the key. A cache key like mymodule.items.{language_id}.{store_id} is needed, otherwise a visitor to the second store will see the cache of the first.

The indexes on (product_id, language_id) and (product_id, store_id) already exist in the core as primary keys, so such a query is fast. For your module's own tables, use the same composite key.

What does store_id = 0 mean and how do settings work?

Zero is the main store, the one configured in "System → Settings". Additional stores have store_id starting from 1 and are created on the store list page.

Store list: the main store comes first and has no record in the store table
Store list: the main store comes first and has no record in the store table · OpenCart 4.1.0.4

The setting table has a store_id column. On catalog startup it loads rows for both 0 and the current store, sorted by store_id ASC. In 3.0 this is a direct query to startup/startup.php, and in 4.1 it goes through model_setting_setting->getSettings(). The current store's rows come second and overwrite the main store's values. The practical result: if the module saved settings only for store_id = 0, an additional store will receive the same values. If you need separate settings for each store, save them with the specific store_id. How this works through editSetting(), and why it deletes the whole code group before inserting, is described in the article on module settings and the setting table.

In the new product form, only store 0 is selected by default (product_store = [0] in both branches). So products created by import or by a custom script without a record in product_to_store do not appear on the storefront at all, even in the main store. This is one of the most common causes of "the product exists in admin but not on the site".

Product form Links tab: the store selection block that writes product_to_store
Product form Links tab: the store selection block that writes product_to_store · OpenCart 4.1.0.4

What happens when a language or store is added or removed?

This is where the versions differ the most, and it is where modules with their own language tables break.

Language list: adding a language triggers copying of all core descriptions
Language list: adding a language triggers copying of all core descriptions · OpenCart 4.1.0.4

Adding a language

In both branches, admin/model/localisation/language.php, method addLanguage(), creates a row in language and copies all core descriptions (attributes, banners, categories, products, options, statuses, and so on) from the config_language_id language, that is, the admin language, into the new one. The method returns the new language_id. The difference is in SEO URLs: OpenCart 3.0 does not copy seo_url records, so you must fill in SEO URLs for the new language yourself. OpenCart 4.1 copies them with the same keywords and adds a language record for each store. The core does not know about your module's tables, so they will have no rows for the new languages.

Removing a language

OpenCart 3.0 (both 3.0.4.1 and 3.0.5.1): deleteLanguage() deletes only the row in language and the seo_url records for that language. Descriptions in product_description and other tables remain as orphans. OpenCart 4.1: deleteLanguage() goes through the models and calls deleteDescriptionsByLanguageId() for each core language table.

Removing a store

setting/store controllerCode that receives a request and prepares data. More in the glossary → in both branches calls deleteStore() and deleteSetting('config', $store_id). OpenCart 3.0: the model deletes only the store row and layout_route; *_to_store and *_to_layout records remain. OpenCart 4.1: the model also cleans up the product, category, information page, manufacturerA product brand. Manufacturers have their own pages. More in the glossary →, theme, and translation bindings for that store.

What the module should do

If you have your own table with language_id, subscribe to the event after addLanguage and copy your rows the same way the core does. Pay attention to the method separator in the trigger: a slash in 3.0, a dot in 4.1.

Example: registering an event when the module is installed

// OpenCart 3.0
$this->load->model('setting/event');
$this->model_setting_event->addEvent(
	'mymodule_language',
	'admin/model/localisation/language/addLanguage/after',
	'extension/module/mymodule/addLanguage'
);

// OpenCart 4.1
$this->load->model('setting/event');
$this->model_setting_event->addEvent([
	'code'        => 'mymodule_language',
	'description' => '',
	'trigger'     => 'admin/model/localisation/language.addLanguage/after',
	'action'      => 'extension/mymodule/module/mymodule.addLanguage',
	'status'      => 1,
	'sort_order'  => 0
]);

Example: handler (the signature is the same for both forms, $output is the new language_id)

public function addLanguage(&$route, &$args, &$output) {
	$new_id = (int)$output;
	$from_id = (int)$this->config->get('config_language_id');

	$this->db->query("INSERT INTO `" . DB_PREFIX . "mymodule_description` (item_id, language_id, title)
		SELECT item_id, '" . $new_id . "', title
		FROM `" . DB_PREFIX . "mymodule_description`
		WHERE language_id = '" . $from_id . "'");
}

To handle language removal, add a second event on deleteLanguage (/before or /after, with the language id in $args[0]), and delete your rows there. In 3.0 this is the only way to avoid accumulating garbage. For how model events work and how the returned value differs between versions, read the articles on intercepting models with events and registering module events.

Common mistakes with language_id and store_id

  • Hardcoded language_id = 1. After reinstalling or removing the English language, the id of Ukrainian may be 2, 3, or 5. Always use config_language_id, and for a specific language, look up the id by code in the language table.
  • Comparing by language code in 4.1 through the session. In 4.1 the language is not stored in the session in catalog; it is set by the language parameter. An AJAX request without this parameter gets the default language, and the module returns texts in the wrong language. Add language to the URL you build for AJAX; examples are in the article on AJAX in OpenCart.
  • A missing *_to_store row when importing or creating entities with custom code. The entity exists in admin but not on the site.
  • Empty descriptions after import for only one language. If the store has two languages and the import writes only one, the second storefront will show empty names (with LEFT JOIN) or hide products (with INNER JOIN).
  • Choosing an order by the current language. order.language_id is the language in which the customer placed the order. Emails and statuses for that customer should be shown in this language, not in the language of the current administrator session.
  • Orphans in 3.0 after removing a language or store. Before migrating to 4.1, find them with a query like SELECT ... FROM product_description pd LEFT JOIN language l ON (l.language_id = pd.language_id) WHERE l.language_id IS NULL and remove them.

If bulk updating descriptions for several languages or stores is a regular task, it is simpler to use a ready-made tool such as product import and export in XLSX and CSV, which writes both descriptions and store bindings. The structure of the product tables itself is covered in the article on the product table and related tables.

Summary

  • Translations live in the *_description tables with a composite key of "id + language_id", and store visibility lives in *_to_store with a key of "id + store_id".
  • Always take the current values from config_language_id and config_store_id: the core sets them at startup. In 3.0 the language comes from the session, cookie, or browser; in 4.1 it comes from the language GET parameter.
  • store_id = 0 is the main store; its settings are the base on which additional store settings are layered.
  • The core copies its own descriptions when a language is added, but not yours. In 3.0 it also does not clean up descriptions when a language is removed, or bindings when a store is removed; in 4.1 it does.
  • A module with its own language tables needs events on addLanguage and deleteLanguage with the correct separator: a slash in 3.0, a dot in 4.1.

Next, consider how to design your module's own tables for several languages and stores. See custom module tables in OpenCart. All articles in this section are collected on the OpenCart Database page.

FAQ

How do I find the language_id of a needed language in code if I only know its code?
Load the localisation/language model and take the language from getLanguages(): in catalog the array is indexed by code, so language_id is in the language_id field of the corresponding element. You can also query the language table directly by the code column.
Can I make a product visible in all stores with a single record?
No, OpenCart has no 'all stores' as a separate value. You need a separate row in product_to_store for each store_id, including 0.
Can I use config_store_id in the admin?
No: the starting admin controllers in 3.0 and 4.1 don't set it, because the admin works with all stores at once. Pass the store explicitly there, from a form or a GET parameter of the page.
What happens to SEO URLs if I delete a language?
In both branches, the seo_url records for that language are deleted along with it. If you later recreate the language, the URLs will have to be restored from a backup or filled in again.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.