XF 2.2 Fetch thousands of rows via Finder / get also the necessary TO_MANY related data with ONE query for each relation

Scandal

Well-known member
Let's say we have to fetch all data via xF2 finder:
PHP:
$data = \XF::finder('Scandals\Addon:Data')->fetch();
This entity has two TO_MANY relations (one is the Attachments).

How could I prepare an output variable which will have all necessary data without leave xF2 to make individual queries for the extra TO_MANY relations?

I can get the primary keys of Data and then run one query for ALL attachments.
Example:
PHP:
        $output = [];
        $ids = [];
        foreach ($data AS $d)
        {
            $output[$d->data_id] = $d;   
            $ids[] = $d->data_id;
        }
        
        if (!empty($ids))
        {
            $attachments = \XF::finder('XF:Attachment')
                            ->with('Data')
                            ->where('content_type', 'sc_data')
                            ->where('content_id', $ids)
                            ->fetch();
                                    
            foreach ($attachments AS $a)
            {
                $output[$a->content_id]['Attachments'][] = $a;
            }   
        }
But it doesn't seem to work.
Any idea?

I need to make ONE query for all attachments and then prepare the final output with them.
 

Scandal

Well-known member
I tried also this:
PHP:
            $att = \XF::finder('XF:Attachment')
                            ->with('Data')
                            ->where('content_type', 'my_content_type')
                            ->where('content_id', $ids)
                            ->fetch();
            $attachments = [];                       
            foreach ($att AS $a)
            {
                $attachments[$a->content_id][] = $a;
            }   

            $attachments = $this->em->getBasicCollection($attachments);
But when I tried to use them via:
HTML:
{{ bb_code($en.message, 'my_content_type', $en, {'attachments': {$attachments.{$en.id}}, 'viewAttachments': true}) }}
The pictures are not showing.

But this still work! ->
HTML:
{{ bb_code($en.message, 'my_content_type', $en, {'attachments': $en.Attachments, 'viewAttachments': true}) }}

Any idea?
 

Scandal

Well-known member
Hey, I just want to reply to my own question, since I find the solution on my own.
For a reference you can use the default xF2's code found on:
XF\Repository\Attachment::addAttachmentsToContent()

This is the way xF2 applies for example the Attachments to all posts of a thread fetched with a Finder, without fetching them with extra queries. (y)
 
Top