PHP
Joomla! 6
Joomla! 5
Joomla! 3 (Legacy)
Database
Basic
Index Query Results by Key with loadObjectList() and loadAssocList()
Eliminates boilerplate re-indexing loops by passing the key column directly into loadObjectList('id') or loadAssocList('code', 'qty').
components/com_example/src/Helper/LookupHelper.php
<?php
declare(strict_types=1);
use Joomla\CMS\Factory;
use Joomla\Database\DatabaseInterface;
$db = Factory::getContainer()->get(DatabaseInterface::class);
$query = $db->getQuery(true)
->select([$db->quoteName('id'), $db->quoteName('alias'), $db->quoteName('title')])
->from($db->quoteName('#__categories'))
->where($db->quoteName('extension') . ' = ' . $db->quote('com_content'))
->setLimit(50, 0);
// Mapa indexado por ID: [10 => stdClass, ...]
$byId = $db->setQuery($query)->loadObjectList('id');
// Mapa chave => valor simples: ['blog' => 'Blog', ...]
$aliasToTitle = $db->setQuery($query)->loadAssocList('alias', 'title');
Chain setLimit($limit, $offset) on the query builder for clean pagination.
components/com_example/src/Helper/LookupHelper.php
<?php
$db = JFactory::getDbo();
$byId = $db->setQuery($query, 0, 50)->loadObjectList('id');
Compatible method signature in Joomla 3 via JFactory::getDbo().
Technical explanation and best practices
Joomla database loaders accept a key column name (and optional value column on loadAssocList()) to return ready-to-use lookup dictionaries in a single call.