Problem with orders and product orders laravel - php

Good evening, I have an orders and orders_products table:
A supplier (user) can upload products to sell them.
If buyer buys a product from different suppliers. That he has for example 3 products buy from different supplier, I want to separate.
For each product purchased from different suppliers it will represent an order for the buyer made by the buyer.
I made my code for the order but I can't seem to place an order for each supplier, please I really need help.
This is my PHP code:
public function validation_commande(Request $request){
$utilisateur = Utilisateur::where('id','=',session('utilisateur'))->first();
$paniers = Panier::where('utilisateur_id','=',$utilisateur->id)->get();
$utilisateur_id = $utilisateur->id;
$mode_paiement_id = 4;
$adresse = Adresse::where('utilisateur_id','=',$utilisateur_id)
->where('adresse_par_defaut','=',1)
->first();
$total_ht = 0;
$total_ttc = 0;
$nombre_produit_panier = count($paniers);
if($nombre_produit_panier >= 1)
{
foreach ($paniers as $c) {
$total_ht += $c->produit->prix_total($c->quantite);
$total_ttc += $c->produit->prix_total_ttc($c->quantite);
$commande = Commande::firstOrCreate([
'utilisateur_id'=>$utilisateur_id,
'fournisseur_id'=>$c->produit->utilisateur_id,
'boutique_id'=>$c->produit->boutique_id,
'statut'=>'en_cours_de_traitement',
'statut_fournisseur'=>'pas_encore_vue_sa_commande',
'total_ht'=>$total_ht,
'total_ttc'=>$total_ttc,
'mode_paiement_id'=>$mode_paiement_id,
'adresse_id'=>$adresse->id,
'date_commande'=>now()
]);
break; }
if($c->achat_groupe == 1){
$achat_groupe = 1;
}else{
$achat_groupe = 0;
}
foreach ($paniers as $c) {
CommandeProduit::create([
'commande_id'=>$commande->id,
'produit_id'=>$c->produit->id,
'prix_ht'=>$c->produit->prix_sans_taxe($c->quantite),
'prix_ttc'=>$c->produit->prix($c->quantite),
'quantite'=>$c->quantite,
'utilisateur_id'=>$utilisateur->id,
'fournisseur_id'=>$c->produit->utilisateur_id,
'boutique_id'=>$c->produit->boutique_id,
'achat_groupe'=>$achat_groupe,
'date_creation'=>now()
]);
}
$message_a_envoye = "**** Market Makers **** \n \n";
$message_a_envoye .= "Une nouvelle commande vient d'arriver";
// $date_du_jour = date("d-m-Y H:i:s");
// $message_a_envoye .= "Date d'inscription : ".$utilisateur->date_creation."\n";
// $this->telegram_send(urlencode($message_a_envoye));
// sleep(3);
$this->telegram_send_2(urlencode($message_a_envoye));
$lien_button = env('APP_URL').'/mes-commandes-b/';
$data = [
'subject' => "Nouvelle commande",
'titre_page' => 'Vous avez reçu une nouvelle commande',
'message' => 'Vous avez reçu une nouvelle commande sur votre espace Market Makers',
'lien_button' => $lien_button,
'message_button' => 'Voir'
];
// Mail::to($c->produit->utilisateur->email)->send(new NotificationMail($data,$c->produit->utilisateur));
Session::flash('success','Votre commande a bien été effectué avec succès');
Panier::where('utilisateur_id', $utilisateur->id)->delete();
$request->session()->put('venue_du_panier',null);
return redirect(route('mes-commandes'));
}
else
{
return redirect(route('mes-commandes'));
}
}
http://pastebin.fr/96873

Related

Ensure no missing column value is sent to INSERT statement

I recently changed my website from shared hosting to a dedicated server (major upgrade..), and some things didn't work out of the box. One of these things was the INSERTs. I was used to code INSERTS without bothering about having all the columns values in my statement. The missing columns were automatically filled with 0s and threw basic warning I ignored.
I thought it was normal MySQL\MariaDB behaviour. With my new dedicated server (not hosted locally), the database sends an error and refuses to insert the line if all the columns values are not declared in the INSERT statement. This is a problem. I add columns, from time to time, in many tables, as I improve the site's functionalities. I don't want to be revising all the INSERTS in the thousands of lines in my PHP scripts every time I add a column to a table.
So, instead, I created this insert function.
Basically:
Call the function, send an array with table name and key+values I want to insert
Function reads the table name, selects one line, and list the columns name
Function prepares an INSERT with the passed key+values, and generates bulk (depending on the types) values for the columns without values passed
Proceed to INSERT
Now the questions:
Is there a simpler way of doing this?
Am I breaching something?
Is it a recurrent need?
And here the function code:
// INSERTION DB GÉNÉRALE
function insert_db($valeurs)
{
global $date;
global $no;
global $bdd;
// Pour le log
$log = 'Valeurs reçues BDD : ';
foreach ($valeurs as $colonne => $valeur)
{
$log .= $colonne.' = '.$valeur.' || ';
};
// On obtient la table dans $valeurs['db_table']
$resultat = $bdd->query('SELECT * FROM '.$valeurs['db_table'].' LIMIT 1');
$tous_les_champs = array_keys($resultat->fetch(PDO::FETCH_ASSOC)); // On crée un tableau avec toutes les entêtes de colonnes
$champs = array(); // Les champs qui seront mis au début de la requête
$valeurs_preparees = array(); // Les valeurs préparées (avec un : devant) pour mettre dans la deuxième portion de la requête
foreach ($tous_les_champs as $champ_unique) // On valide qu'on a des données pour chaque colonne
{
$valeur = "0";
if (strpos($champ_unique, 'DATE') !== false) { $valeur = $date; }; // Si le titre du champs contiens « DATE », on prends en considération qu'il faut y mettre quelque chose en type datetime
if (strpos($champ_unique, 'RAW_DN') !== false) { $valeur = "0000-00-00 00:00:00"; }; // Pour le champs custom de date de naissance de USAGERS
if (strpos($champ_unique, 'DATE_DEPART') !== false) { $valeur = "0000-00-00 00:00:00"; }; // Si le titre du champs contiens « DATE », on prends en considération qu'il faut y mettre quelque chose en type datetime
if (strpos($champ_unique, 'DESCRIPTION') !== false) { $valeur = "Aucune description"; };
if (strpos($champ_unique, 'COMMENTAIRE') !== false) { $valeur = "Aucun commentaire"; };
if (strpos($champ_unique, 'CREE_PAR') !== false) { $valeur = $_SESSION['DOCTUS'][$no]['ID']; };
if (strpos($champ_unique, 'MODIF_PAR') !== false) { $valeur = $_SESSION['DOCTUS'][$no]['ID']; };
if (strpos($champ_unique, 'CREATEUR') !== false) { $valeur = $_SESSION['DOCTUS'][$no]['ID']; };
if (strpos($champ_unique, 'MODIFICATEUR') !== false) { $valeur = $_SESSION['DOCTUS'][$no]['ID']; };
if (strpos($champ_unique, 'PAYE_') !== false) { $valeur = "1"; };
if (!isset($valeurs[$champ_unique]) || $valeurs[$champ_unique] == "") { $tableau[$champ_unique] = $valeur; }else{ $tableau[$champ_unique] = $valeurs[$champ_unique]; }; $champs[$champ_unique] = $champ_unique; $valeurs_preparees[$champ_unique] = ":".$champ_unique;
};
// On crée les champs pour la requête
$requete_champs = "";
foreach ($champs as $champ_unique)
{
if ($requete_champs != "") { $requete_champs .= ', '; };
$requete_champs .= $champ_unique;
};
// On crée les valeurs pour la requête
$requete_valeurs = "";
foreach ($valeurs_preparees as $valeur_unique)
{
if ($requete_valeurs != "") { $requete_valeurs .= ', '; };
$requete_valeurs .= $valeur_unique;
};
$req_insert_db = $bdd->prepare('INSERT INTO '.$valeurs['db_table'].'('.$requete_champs.') VALUES('.$requete_valeurs.')');
$req_insert_db->execute($tableau);
$id_insert = $bdd->lastInsertId();
// On log l'insertion
$log .= "\n ID inséré : ".$id_insert;
if ($id_insert == 0) { $log .= ' || ERREUR'; };
$fichier = './log/insertions_log.txt';
file_put_contents($fichier, $log, FILE_APPEND);
return $id_insert;
};
The cause is a different configuration of MySql/MariaDb server between old and new server
(see the documentation of Strict SQL Mode for more details).
The cleanest way is to do an ALTER TABLE of all your tables and give to any fields a DEFAULT value (at least to all fields that you don't want to specify a value): in this case the engine don't need all fields in INSERT statements. (see this answer to see the syntax)

Doctrine ODM memory limit reached when inserting documents

I have a little problem, I'm getting around 800 000 datas from a json and I'm trying to insert them into a MongoDB Database. But I reach memory limit (I've set it up to 8GB for testing) while doing this. I think my script isn't optimized but I can't find where. Can you guys help me ? Here is the script :
$jsonResponse = json_decode($content->response);
$datas = $jsonResponse->hits->hits;
// On crée la collection si elle n'éxiste pas
$collection = $connection->createCollection($table->getTableName(), false );
// On enregistre les données dans la collection
foreach ($datas as $data)
{
if(!empty($data) || $data)
{
$document['_id'] = $data->_id; // ID netwoof unique
$document['_updated'] = substr($data->_source->_updated, 0, -3); // Date de dernière MàJ des données
$document['_url'] = $data->_source->_url; // Start URL
// On enregistre ensuite chaque champs définis dans le dashboard
foreach ($fields as $field)
{
// On récupère le nom du champs netwoof
$containerFieldName = $field->getContainerFieldName();
// On fait correspondre notre champ db avec celui netwoof
if( isset( $data->_source->$containerFieldName ) && (!empty($data->_source->$containerFieldName) || $data->_source->$containerFieldName == 0 ) )
$document[$field->getFieldName()] = $data->_source->$containerFieldName;
/*else
$document[$field->getFieldName()] = null;*/
}
foreach ($customFields as $customField)
{
if(!empty($customField->getFieldValue()))
$document[$customField->getFieldName()] = $customField->getFieldValue();
}
// Enregistrement des données
$collection->save($document);
}
// On réinitialise la variable
unset($document);
}
Thanks all for your answer and sorry for my english.

SQL LIKE this OR that

I'm trying to do:
(i'm working with codeignitor)
$conditions = $tri." LIKE'%".$prenomNom."%' OR LIKE'%".$nomPrenom."%'";
I also tried:
$conditions = ($tri." LIKE '%".$prenomNom."%' OR ".$tri." LIKE '%".$nomPrenom."%'");
But the OR doesn't work... my request return only $tri like $nameLastname.
When i do echo of $nameLastname and $LastnameName everything is ok.
My code
public function rechercheParAuteur($selection = "*", $recherche = "", $tri = "", $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
//$conditions = "titre LIKE '%".$recherche."%'"; //création de la condition personnalisée
$testrecherche = str_replace("'","\'", $recherche);
$rechercheArray = explode(" ", $testrecherche);
if (isset($rechercheArray[1]))
{
$nomPrenom = $rechercheArray[0]." ".$rechercheArray[1];
$prenomNom = $rechercheArray[1]." ".$rechercheArray[0];
//$conditions = $tri." LIKE'%".$prenomNom."%' OR LIKE'%".$nomPrenom."%'";
$conditions = ($tri." LIKE '%".$prenomNom."%' OR ".$tri." LIKE '%".$nomPrenom."%'");
//echo $nomPrenom; OK
//echo $prenomNom; OK
}
else
{
$resultat = $rechercheArray[0];
$conditions = $tri." LIKE '%".$resultat."%'";
}
$retour= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $retour;
You probably want to put the condition in perens.
$conditions = "($tri LIKE '%$prenomNom%' OR $tri LIKE '%$nomPrenom%')";

Notice when using an object

I have this simple request :
if($donnees->pays == 1)
{
$sql = "SELECT code_postal, nom as nom_ville FROM localite_be WHERE id = ".$donnees->code_postal_off;
}
elseif($donnees->pays == 2)
{
$sql = "SELECT code_postal, nom as nom_ville FROM localite_fr WHERE id = ".$donnees->code_postal_off;
}
else
{
$sql = "SELECT code_postal, nom as nom_ville FROM localite_lux WHERE id = ".$donnees->code_postal_off;
}
$cp_ville = $bdd->prepare($sql);
$cp_ville->execute();
$res_cp_ville = $cp_ville->fetch(PDO::FETCH_OBJ);
I obtain an object :
stdClass Object
(
[code_postal] => 7060
[nom_ville] => SOIGNIES
)
stdClass Object
(
[code_postal] => 7134
[nom_ville] => RESSAIX
)
and this notice :
Notice: Trying to get property of non-object in /home/web998/public_html/classes/Excel/Classes/impression_xlsx_demandes_agrements.php on line 561
Notice: Trying to get property of non-object in /home/web998/public_html/classes/Excel/Classes/impression_xlsx_demandes_agrements.php on line 562
Lines 561 and 562 are the followings :
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$i, $res_cp_ville->code_postal);
$objPHPExcel->getActiveSheet()->SetCellValue('H'.$i, $res_cp_ville->nom_ville);
echo "<pre>";
print_r($res_cp_ville);
echo "</pre>";
This is the whole code :
//je crée une nouvelle sheet Excel
$objPHPExcel->createSheet();
//je la mets en active
$objPHPExcel->setActiveSheetIndex(1)->setTitle('Demandes de renouvellements');
//Demandes de renouvellements
$sql = "SELECT pharmacien.*,
officine.ref_type_officine,
officine.telephone,
officine.mail,
officine.province,
officine.adresse as addr_off,
pays.libelle,
province_be.nom as prov,
officine.ref_code_postal as code_postal_off
FROM pharmacien
LEFT JOIN agrement
ON pharmacien.ref_agrement = agrement.id
LEFT JOIN officine
ON pharmacien.ref_identification = officine.ref_identification
LEFT JOIN pays
ON pharmacien.pays = pays.id
LEFT JOIN province_be
ON officine.province = province_be.ID
WHERE ( date_soumission IS NOT NULL AND ref_type_agrement = '2' )
";
//echo $sql;
$pharmaciens = $bdd->prepare($sql);
$pharmaciens->execute();
$res = $pharmaciens->fetchAll(PDO::FETCH_OBJ);
$i = 2;
$temp_nombre_jours = 0;
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'NOM');
$objPHPExcel->getActiveSheet()->SetCellValue('B1', 'PRENOM');
$objPHPExcel->getActiveSheet()->SetCellValue('C1', 'TYPE OFFICINE');
$objPHPExcel->getActiveSheet()->SetCellValue('D1', 'PAYS');
$objPHPExcel->getActiveSheet()->SetCellValue('E1', 'PROVINCE');
$objPHPExcel->getActiveSheet()->SetCellValue('F1', 'ADRESSE OFFICINE');
$objPHPExcel->getActiveSheet()->SetCellValue('G1', 'CP OFFICINE');
$objPHPExcel->getActiveSheet()->SetCellValue('H1', 'VILLE OFFICINE');
$objPHPExcel->getActiveSheet()->SetCellValue('I1', 'TELEPHONE');
$objPHPExcel->getActiveSheet()->SetCellValue('J1', 'MAIL');
foreach($res as $donnees)
{
$styleArray = array('font' => array('bold' => true));
//je mets en gras le contenu de ces cellules
$objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('B1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('C1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('D1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('E1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('F1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('G1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('H1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('I1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('J1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->getStyle('K1')->applyFromArray($styleArray);
$objPHPExcel->getActiveSheet()->SetCellValue('A'.$i, $donnees->nom);
$objPHPExcel->getActiveSheet()->SetCellValue('B'.$i, $donnees->prenom);
if($donnees->ref_type_officine == 1)
{
$objPHPExcel -> getActiveSheet() -> setCellValue('C'.$i, 'Officine ouverte au public');
}
else
{
$objPHPExcel -> getActiveSheet() -> setCellValue('C'.$i, 'Officine hospitaliere');
}
//pays
if($donnees->pays == 1)
{
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$i, "BELGIQUE");
}
elseif($donnees->pays == 2)
{
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$i, "FRANCE");
}
else
{
$objPHPExcel->getActiveSheet()->SetCellValue('D'.$i, "LUXEMBOURG");
}
//province
$objPHPExcel->getActiveSheet()->setCellValue('E'.$i, $donnees->prov);
$objPHPExcel->getActiveSheet()->setCellValue('F'.$i, $donnees->addr_off);
if($donnees->pays == 1)
{
$sql = "SELECT code_postal, nom as nom_ville FROM localite_be WHERE id = ".$donnees->code_postal_off;
}
elseif($donnees->pays == 2)
{
$sql = "SELECT code_postal, nom as nom_ville FROM localite_fr WHERE id = ".$donnees->code_postal_off;
}
else
{
$sql = "SELECT code_postal, nom as nom_ville FROM localite_lux WHERE id = ".$donnees->code_postal_off;
}
$cp_ville = $bdd->prepare($sql);
$cp_ville->execute();
$res_cp_ville = $cp_ville->fetch(PDO::FETCH_OBJ);
$objPHPExcel->getActiveSheet()->SetCellValue('G'.$i, $res_cp_ville->code_postal);
$objPHPExcel->getActiveSheet()->SetCellValue('H'.$i, $res_cp_ville->nom_ville);
$objPHPExcel->getActiveSheet()->SetCellValue('I'.$i, $donnees->telephone);
$objPHPExcel->getActiveSheet()->SetCellValue('J'.$i, $donnees->mail);
$i = $i+1;
}//fin du foreach
//redimensionnement des colonnes afin d'avoir des colonnes en autosize
for($col = 'A'; $col !== 'L'; $col++)
{
$objPHPExcel->getActiveSheet()
->getColumnDimension($col)
->setAutoSize(true);
}
I thing you are trying to export data to excel.
Have you created object $objPHPExcel = new Excel(); with your excel class.

Undefined index error upon $em->clear() in Symfony2

I have written a Symfony command to import some data from an API. It works but the problem is my PHP memory usage increases when I insert a big JSON in my database. And my unitOfWork increases by '2' to after each activty import.
I have already unset all my used objects, and I have read the documentation of Symfony2 when you want to do massive batch: http://www.doctrine-project.org/blog/doctrine2-batch-processing.html
But when I use $em->clear() my entity manager gives this error:
Notice: Undefined index: 000000007b56ea7100000000e366c259 in path-to-application\vendor\doctrine\lib\Doctrine\ORM\UnitOfWork.php line 2228
Here is my complete code :
/**
* #see Command
*/
protected function configure() {
$this
->setName('ks:user:runkeepersync')
->setDescription('Synchroniser les activités d\'un utilisateur runkeeper')
->setDefinition(array(
new InputArgument('access_token', InputArgument::REQUIRED, 'Access token'),
))
}
/**
* #see Command
*/
protected function execute(InputInterface $input, OutputInterface $output) {
$accessToken = $input->getArgument('access_token');
$em = $this->getContainer()->get('doctrine')->getEntityManager();
$UserHasServices = $em->getRepository('KsUserBundle:UserHasServices')->findOneByToken($accessToken);
if (!is_object($UserHasServices) ) {
echo "Impossible de trouver l'utilisateur qui possède le jeton ".$accessToken."";
}
$user = $UserHasServices->getUser();
$service = $UserHasServices->getService();
echo "avant de requérir l'api : ".memory_get_usage()."\n";
try {
$rkApi = $this->getContainer()->get('ks_user.runkeeper');
$rkApi->setAccessToken($accessToken);
$activities = $rkApi->getFitnessActivities(0,25);
$nbParPages = 25;
$nomberActivitites = $activities->size;
$aActivities = $activities->items;
$nbPages = floor ($nomberActivitites/$nbParPages);
$aEndurance = array("Running", "Cycling", "Mountain Biking", "Walking", "Hiking", "Downhill Skiing", "Cross-Country Skiing", "Snowboarding", "Skating","Wheelchair", "Rowing", "Elliptical", "Other");
$aEnduranceUnderWater = array("Swimming");
$enduranceOnEarthType = $em->getRepository('KsActivityBundle:SportType')->findOneByLabel("endurance");
if (!is_object($enduranceOnEarthType) ) {
echo "Impossible de trouver le type de sport d'endurance";
}
$enduranceUnderWaterType = $em->getRepository('KsActivityBundle:SportType')->findOneByLabel("endurance_under_water");
if (!is_object($enduranceUnderWaterType) ) {
echo "Impossible de trouver le type de sport d'endurance sous l'eau ";
}
echo "Après avoir récupéré 25 activités : ".memory_get_usage()."\n";
$a = 0;
for($i=0;$i<=$nbPages;$i++){
if($i!=0){
$activities = $rkApi->getFitnessActivities($i,25);
$aActivities = $activities->items;
}
foreach ($aActivities as $activity) {
$a = $a+1;
$codeSport = $this->formatNameSport($activity->type);
$sport = $em->getRepository('KsActivityBundle:Sport')->findOneByCodeSport($codeSport);
if (!is_object($sport) ) {
$sport = new \Ks\ActivityBundle\Entity\Sport();
$sport->setLabel($codeSport);
$sport->setCodeSport($codeSport);
$sport->setSportType($enduranceOnEarthType);
$em->persist($sport);
$em->flush();
}
$activityDetail = json_decode($rkApi->requestJSONHealthGraph($activity->uri));
if(in_array($activity->type, $aEndurance)){
$urlActivitieDetail = $activityDetail->activity;
$ActivitySessionEnduranceOnEarth = new \Ks\ActivityBundle\Entity\ActivitySessionEnduranceOnEarth($user);
isset($activity->total_distance)? $ActivitySessionEnduranceOnEarth->setDistance($activity->total_distance) : "";
isset($activity->duration)? $ActivitySessionEnduranceOnEarth->setDuration($this->secondesToTimeDuration($activity->duration)) : "";
isset($activity->start_time)? $ActivitySessionEnduranceOnEarth->setIssuedAt(new \DateTime($activity->start_time)) : "";
$ActivitySessionEnduranceOnEarth->setModifiedAt(new \DateTime('Now'));
$ActivitySessionEnduranceOnEarth->setSport($sport);
isset($activityDetail->total_calories)? $ActivitySessionEnduranceOnEarth->setCalories($activityDetail->total_calories) : "";
isset($activityDetail->climb)? $ActivitySessionEnduranceOnEarth->setElevationGain($activityDetail->climb) : "";
$maxElevation = 0;
$minElevation = 10000;
if(isset($activityDetail->path)){
foreach($activityDetail->path as $gpsPoint){
if($gpsPoint->altitude > $maxElevation){
$maxElevation = $gpsPoint->altitude;
}
if($gpsPoint->altitude < $minElevation){
$minElevation = $gpsPoint->altitude;
}
}
$ActivitySessionEnduranceOnEarth->setElevationMin($minElevation);
$ActivitySessionEnduranceOnEarth->setElevationMax($maxElevation);
}
$em->persist($ActivitySessionEnduranceOnEarth);
$em->flush();
//Pour chaque activité on a un identifiant relatif au service qu'on synchronise
$ActivityComeFromService = new \Ks\ActivityBundle\Entity\ActivityComeFromService();
$ActivityComeFromService->setActivity($ActivitySessionEnduranceOnEarth);
$ActivityComeFromService->setService($service);
$ActivityComeFromService->setIdWebsiteActivityService($activity->uri);
$ActivityComeFromService->setSourceDetailsActivity($rkApi->requestJSONHealthGraph($activity->uri));
$ActivityComeFromService->setTypeSource("JSON");
$em->persist($ActivityComeFromService);
$em->flush();
echo "Import de l'activite num ".$a." type :".$activity->type." effectue avec success \n";
unset($ActivitySessionEnduranceOnEarth);
unset($ActivityComeFromService);
echo "UnitOFWOrk -> ".$em->getUnitOfWork()->size()."\n";
}
if(in_array($activity->type, $aEnduranceUnderWater)){
$ActivitySessionEnduranceUnderWater = new \Ks\ActivityBundle\Entity\ActivitySessionEnduranceUnderWater($user);
isset($activity->total_distance)? $ActivitySessionEnduranceUnderWater->setDistance($activity->total_distance) : "";
isset($activity->duration)? $ActivitySessionEnduranceUnderWater->setDuration($this->secondesToTimeDuration($activity->duration)) : "";
isset($activity->start_time) && !empty($activity->start_time)? $ActivitySessionEnduranceUnderWater->setIssuedAt(new \DateTime($activity->start_time)) : "";
$ActivitySessionEnduranceUnderWater->setModifiedAt(new \DateTime('Now'));
$ActivitySessionEnduranceUnderWater->setSport($sport);
isset($activityDetail->total_calories)? $ActivitySessionEnduranceUnderWater->setCalories($activityDetail->total_calories) : "";
isset($activityDetail->notes)? $ActivitySessionEnduranceUnderWater->setDescription($activityDetail->notes) : "";
$em->persist($ActivitySessionEnduranceUnderWater);
$em->flush();
$ActivityComeFromService = new \Ks\ActivityBundle\Entity\ActivityComeFromService();
$ActivityComeFromService->setActivity($ActivitySessionEnduranceUnderWater);
$ActivityComeFromService->setService($service);
$ActivityComeFromService->setIdWebsiteActivityService($activity->uri);
$ActivityComeFromService->setSourceDetailsActivity($rkApi->requestJSONHealthGraph($activity->uri));
$ActivityComeFromService->setTypeSource("JSON");
$em->persist($ActivityComeFromService);
$em->flush();
echo "Import de l'activité num ".$a." type :".$activity->type." effectué avec succès\n";
unset($ActivitySessionEnduranceUnderWater);
unset($ActivityComeFromService);
}
echo "Après chaque activité : ".memory_get_usage()."\n";
unset($sport);
unset($activityDetail);
$em->clear();
}
}
} catch (\Exception $e) {
throw $e;
}
}
Thanks, #AdrienBrault. I have tested with --env=prod --no-debug, and it is true that it consumes less memory, but the memory still increase. How can I really clear the entity manager? and stabilize the memory?
Symfony logs all SQL queries in dev environment, so first you need to disable it
// disable logger
$em->getConnection()->getConfiguration()->setSQLLogger(null);
You may use event listeners on entities, it may also increase memory usage. You can disable them like so
// remove all listeners
foreach ($em->getEventManager()->getListeners() as $event => $listeners) {
foreach ($listeners as $listener) {
$em->getEventManager()->removeEventListener($event, $listener);
}
}
Remove unset from your code, there is no need for them, as you clear entity manager every step of your loop.
// save and clear
$em->flush();
$em->getUnitOfWork()->clear();
Remember that doctrine can optimize your queries, and improve perfomance if you group queries into one flush. So the best practice would be to execute flush once over some parts of your data. For example:
// collect 100 entities and then save them
if (($i % 100) == 0) {
$em->flush();
$em->getUnitOfWork()->clear();
}
Try to reset the entity manager with:
$this->getContainer()->get('doctrine')->resetEntityManager();
and then:
$em = $this->getContainer()->get('doctrine')->getEntityManager();

Categories