XF 2.0 Order by FIELD with the entity finder system?

Jaxel

Well-known member
I have an array of IDs. I want to fetch from a table, all items that match those IDs... But I also want the results to match the order of the original array.

If I were to do this in pure MySQL, I would do the following:
Code:
SELECT *
    FROM ewr_medio_media
WHERE media_id IN('9292','9301','9290')
ORDER BY FIELD(media_id, '9292','9301','9290')

Is something like this possible with the entity system?
 
I got this working:
Code:
        $mediaIDs = $this->db()->quote($playlist->playlist_media);
       
        $medias = $this->db()->fetchAll("
            SELECT *
                FROM ewr_medio_media
            WHERE media_id IN( $mediaIDs )
            ORDER BY FIELD(media_id, $mediaIDs )
        ");
       
        foreach ($medias AS &$media)
        {
            $media = \XF::em()->instantiateEntity('EWR\Medio:Media', $media);
        }

Is it bad form to do what I did?
 
I guess it's fine, because this is ultimately what the finder itself does. ( $this->db->query($q)->fetchAll(); )
 
You can use a finder expression with order():

PHP:
$finder = \XF::finder('Vendor\Addon:Entity');
$entities = $finder
    ->order($finder->expresssion('FIELD(%s, 1, 2, 3)', 'column_name'))
    ->fetch();
 
Last edited:
Top Bottom