Is there a way to retrieve associations for a given contact with a single call and if not - how would I obtain associations for a given contact with a separate call? I cannot seem to be able to find any resource that would show that.
Currently I’m getting the the contact using one of the examples from the API documentation:
$filter = new Filter;
$filter->setOperator(Filter::OPERATOR_EQ)
->setPropertyName('email')
->setValue($email);
$filterGroup = new FilterGroup;
$filterGroup->setFilters([$filter]);
$searchRequest = new PublicObjectSearchRequest;
$searchRequest->setFilterGroups([$filterGroup]);
$searchRequest->setProperties([
'firstname',
'lastname',
'email',
'company',
'website',
]);
$response = $this->discovery
->crm()
->contacts()
->searchApi()
->doSearch($searchRequest);
if (!$response->valid()) {
throw new ErrorException(
$response?->getMessage() ?? 'Api response returned error'
);
}
return $response->getResults()[0]->getProperties();
Hello @ssulinski
Right now it’s not possible to fetch an association with the contact within the single API call, first, run an API to fetch the contact and then run an API call to fetch the associated object.
@ssulinskiIf possible, could you please share your code on how did you get contact with the association? I’m also working on same things.
@KPadhiyar here’s the method I’ve created to obtain company associations for a given contact id (I’m using Laravel and its Collection in this example):
public function getContactToCompanyAssociations(int $contact_id): Collection
{
$response = $this->discovery
->crm()
->associations()
->v4()
->batchApi()
->getPage(
from_object_type: '0-1',
to_object_type: '0-2',
batch_input_public_fetch_associations_batch_request: new BatchInputPublicFetchAssociationsBatchRequest([
'inputs' => [['id' => $contact_id]],
])
);
if (! $response->valid()) {
throw new ErrorException(
$response?->getMessage() ?? 'Api response returned error'
);
}
if (! $results = $response->getResults()) {
return new Collection;
}
return collect($results)
->pluck('to')
->flatMap(function (array $companies) {
return array_map(
fn (MultiAssociatedObjectWithLabel $company) => $company->getToObjectId(),
$companies
);
});
}
The `discovery` property is the constructor injected instance of `HubSpot\Discovery\Discovery`