The sum of the items in contain

I have query:

        $Query = $this->UsersDocuments->find()->select([
        'UsersDocuments.id',
        'UsersDocuments.order_number',
    ])
        ->contain([
            'UsersDocumentsOrders',
            'UsersDocumentsItems'
        ]);
    
    $Content = $this->paginate($Query);

I need to calculate the sum of the items in the UsersDocumentsItems table that is assigned to the UsersDocuments table. Will there be any function in the contain?

Thank you

Try to look this !!! check this url

I don’t see an example with contain there. Could you give me an example of my query?

It may be better to make the database do the sum using SQL functions

$query = $this->UsersDocuments->find()
    ->select([
        'UsersDocuments.id',
        'UsersDocuments.order_number',
    ])
    ->leftJoinWith('UsersDocumentsItems');
$query
    ->select([
        'item_count' => $query->func()->count(['UsersDocumentsItems.id'])
    ])
    ->group(['UsersDocuments.id']);

You can call contain and/or other functions

1 Like