I need to import records from an API (TeamLeader API 'old one').
I am using an ajax request to loop 5 times through the API "pages". The API has about 400 records and the limit to request is 100 at a time.
Ajax Request:
<button id="ajax" type="button" class="btn btn-primary ajax" title="Ajax Request">
Import
</button>
<div class="card-body">
<div class="ajax-content"></div>
</div>
<script type="text/javascript">
$('#ajax').click(function () {
$('.ajax-content').html('');
getAjax(0);
});
var cur = 0;
function getAjax(cur) {
$.ajax({
url: 'import/'+cur, success: function (result) {
if(result == 0 && cur < 9)
{
getAjax(cur+1)
}else{
$('.ajax-content').html('<hr>Import finished. Records : ' + result)
}
}
})
}
</script>
Then i have the controller to add the records to the database. The idea is to add all the records to the database and skip the records that already are in there.
Trying my best to explain the idea of this all:
- So you import the records
- The ajax request loops 5 times through the api to get all the records
- The records get added in the database and skips the records that already are in there with an unique id : 'TlId'
Controller:
/**
* @Route("/import/{page}", name="import_company")
*/
public function importCompany($page, LoggerInterface $logger, CompanyRepository $companyRepository): Response
{
$fields = array(
"api_group" => ("XXXXX"),
"api_secret" => ("XXXXX"),
"amount" => ("100"),
"pageno" => ($page),
);
$client = HttpClient::create();
$response = $client->request('POST', "https://app.teamleader.eu/api/getCompanies.php", [
'body' => $fields,
]);
$content = $response->getContent();
$results = json_decode($content, true);
$id = $companyRepository->findAllByTlId();
$ids = array_column($id, "TlId");
$number = 0;
foreach ($results as $item) {
if (!in_array($item['id'], $ids)) {
$number ++;
$company = new Company();
$company
->setTlId($item['id'])
->setName($item['name'])
->setWebsite($item['website'])
->setType(null)
->setBillingAddress($item['street']. ' ' . $item['number'])
->setBillingZip($item['zipcode'])
->setBillingTown($item['city'])
->setEmail($item['email'])
->setPhone($item['telephone'])
->setFax($item['fax']);
$this->em->persist($company);
}
$this->em->flush();
return new Response($number);
}
So the problem is that the ajax loops 1 time and get 1 record. after that it stops and shows the amount of records he got '1'.
If i try it again there is this exeption and error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '6837317' for key 'xxx'
And the exeption that tried to insert the values that already are in there.
I think the problem is in de controller but i can't figure it out. Maybe someone can see the problem, Thanks!