XF 2.1 How to get a subset of columns from an entity using finder()

abdfahim

Well-known member
For example, say in a portal page, I just need the User entity and first 5 columns of a custom XF:TestAddon entity. How can I fetch only those 5 columns using finder() instead of fetching all as below?

PHP:
$finder = $this->finder('AbdFahim\TestAddon:TestAddon');
$results = $finder->with('User', true)->fetch();

So, basically, I would like to replace SELECT * ....... to SELECT col1, col2, col3, col4, col5 ...... which might be a bit more optimized in my scenario?


PHP:
public static function getStructure(Structure $structure)
    {
        $structure->table = 'xf_abdfahim_testaddon';
        $structure->shortName = 'XF:TestAddon';
        $structure->primaryKey = 'user_id';
        $structure->columns = [
            'user_id' => ['type' => self::UINT, 'required' => true],
            'col1' => ['type' => self::STR, 'nullable' => true, 'default' => null],
            'col2' => ['type' => self::STR, 'nullable' => true, 'default' => null],
            'col3' => ['type' => self::STR, 'nullable' => true, 'default' => null],
            'col4' => ['type' => self::STR, 'nullable' => true, 'default' => null],
            'col5' => ['type' => self::STR, 'nullable' => true, 'default' => null]
             ..................................................
             ..................................................
            'col30' => ['type' => self::STR, 'nullable' => true, 'default' => null]
        ];
        $structure->getters = [];
        $structure->relations = [
            'User' => [
                'entity' => 'XF:User',
                'type' => self::TO_ONE,
                'conditions' => 'user_id',
                'primary' => true
            ],
        ];

        return $structure;
    }
 
Last edited:
You can do $finder->fetchOnly(['column1', 'column2']), but this will not give you an entity. As far as I know, entities require the entire set of data to work properly. The performance of SELECT cols vs SELECT * may be better relatively, but it's unlikely to have any real (discernible) performance impact.
 
Pagination/result limiting is probably more efficient than any (negligible) performance boost you'd gain by not over-fetching columns.
 
Back
Top Bottom