Nitish Kumar
Nitish Kumar

Reputation: 6276

How to use laravel collection methods

I'm trying to query a nested relation and getting the count of distant model count, I'm transforming this to a variable but it is not happening:

$companies = Company::where('is_client', '=', 1)
    // load count on distant model
    ->with(['interactionSummaries.interaction' => function ($q) {
        $q->withCount(['contactsAssociation' => function ($q) {
            $q->whereHas('company', function ($q) {
                $q->where('type', 'like', 'Research');
            });
        }]);
    }])
    ->get()
    ->transform(function ($company) {
        $company->contacts_association_count = $company->interactionSummaries
            ->pluck('interaction.contacts_association_count')
            ->collapse()
            ->sum();
    });

When I try to dd($companies) or even return $companies I get null values placed in each array index

Null values in array keys

But when I do dd($company) inside transform

->transform(function ($company) {
    $company->contacts_association_count = $company->interactionSummaries
        ->pluck('interaction.contacts_association_count')
        ->collapse()
        ->sum();
    dd($company);
});

I get the single collection which states my query is running properly:

single instance

If I remove transform part and simply get the collection:

$companies = Company::where('is_client', '=', 1)
    // load count on distant model
    ->with(['interactionSummaries.interaction' => function ($q) {
        $q->withCount(['contactsAssociation' => function ($q) {
            $q->whereHas('company', function ($q) {
                $q->where('type', 'like', 'Research');
            });
        }]);
    }])
    ->get()

I'm getting the desired output, But I don't know what it is happening after transform execution. In fact it is not plucking and adding the sum, as I'm getting all 0 in the counts.

collection count

I've marked them with red. Help me out in this

Upvotes: 0

Views: 298

Answers (2)

Hallo Hallo
Hallo Hallo

Reputation: 1

You need to put return $company statement in transform.

Upvotes: 0

omitobi
omitobi

Reputation: 7334

I think you are missing a return statement in the transform closure.

Upvotes: 2

Related Questions