Search code examples
pimcore

How to select only needed fields of objects?


I am using the Pimcore API to fetch objects.

$myObjects = new Object\MyObject\Listing();
$myObjects->load();

$myObjects->getObjects();

Works as expected. Now I want to select only a specific field of my objects, e.g. the name field.

How can I tell Pimcore to select only fields that I want? Is it even possibile through the API or do I need to use custom SQL? If so, how can I do that?

Best regards


Solution

  • The pimcore listing is always returning the complete set of objects matching your listing condition...

    If you want a fast and easy way to only select one field of your object, I recommend to use the pimcore db class:

    $db = \Pimcore\Db::get();
    $fieldsArray = $db->fetchCol("SELECT `YOUR_FIELD` FROM `object_query_CLASS-ID`");
    

    This will return you an array width all 'YOUR_FIELD' values from the object query table of your class.


    To get the class ID for your query dynamically your should use:

    $classId = \Pimcore\Model\Object\MyObject::classId();
    

    Edit:

    To get more than one field column, you need to use 'fetchAll' instead of 'fetchCol':

     $fieldsArray = $db->fetchAll("SELECT `YOUR_FIELD`, `YOUR_FIELD_2` FROM `object_query_CLASS-ID`");