Symfony 4 - some difficults with make a Doctrine findBy with parameters - function

I took over an old project under Symfony 4, which I would like to improve.
I have pages that use pagination, with a service that I created that takes parameters like class, maximum number of elements per page, and so on.
On one of my pages, I added a search field to filter by name the display of a list.
To give you an idea of the function that returns the data:
/**
* Permet de récupérer les données paginées pour une entité spécifique
*
* Elle se sert de Doctrine afin de récupérer le repository pour l'entité spécifiée
* puis grâce au repository et à sa fonction findBy() on récupère les données dans une
* certaine limite et en partant d'un offset
*
* #throws Exception si la propriété $entityClass n'est pas définie
*
* #return array
*/
public function getData()
{
if (empty($this->entityClass)) {
throw new \Exception("Vous n'avez pas spécifié l'entité sur laquelle nous devons paginer ! Utilisez la méthode setEntityClass() de votre objet PaginationService !");
}
// 1) Calculer l'offset
$offset = $this->currentPage * $this->limit - $this->limit;
// 2) Demander au repository de trouver les éléments à partir d'un offset et
// dans la limite d'éléments imposée (voir propriété $limit)
return $this->manager
->getRepository($this->entityClass)
->findBy([], [], $this->limit, $offset);
}
So now my goal is to ensure that the function can handle the case when I asked him to sort in the results due to a request DQL example.
On one of my pages, thanks to the search filter, I have to enter the first name or the name of a user (or some characters are enough).
This translates to the following DQL query:
public function getUsersByName($name)
{
return $this->createQueryBuilder('u')
->where('u.nom LIKE :name OR u.prenom LIKE :name')
->setParameter('name', $name . '%')
->orderBy('u.nom', 'ASC')
->getQuery()
->getResult();
}
How could I integrate this into my function? The goal being to do that for any query eventually. I just need to add the limit and the offset to the result
EDIT:
Is is possible to make something like :
$function = getUsersByName;
$parameters = $this->name;
return $this->manager
->getRepository($this->entityClass)
->$function($parameters);

If I'm not wrong, you just need to replace :
return $this->manager
->getRepository($this->entityClass)
->findBy([], [], $this->limit, $offset);
by :
return $this->manager
->getRepository($this->entityClass)
->getUsersByName($name, $this->limit, $offset);
Assuming you changed the method in your Repo for :
public function getUsersByName($name, $limit = null, $offset = 0)
{
$query = $this->createQueryBuilder('u')
->where('u.nom LIKE :name OR u.prenom LIKE :name')
->setParameter('name', $name . '%')
->orderBy('u.nom', 'ASC');
if($limit){
$query->setFirstResult($offset)
->setMaxResults($limit);
}
return $query->getQuery()
->getResult();
}
Did I understand your problem well ?

Related

How to find json data?

chitown88 help me to find the json on this website : https://www.iwc.com/fr/fr/watch-collections/pilot-watches/iw329303-big-pilots-watch-43.html
It seems that you need to replace html by .productinfo.FR.json
Source : How to scrape specific information on a website
I would like to do the same output with this page : https://www.omegawatches.com/fr-fr/watch-omega-constellation-quartz-27-mm-12315276005001
But I cannot manage to scrape those informations because the page is dynamic and I cannot find the json data, I searched for hours.
Do you have any solutions in order to scrape the same output than the question source ?
There isn't anything special about this page. Just grab the right information with beautifulsoup:
import requests
from bs4 import BeautifulSoup
url = "https://www.omegawatches.com/fr-fr/watch-omega-constellation-quartz-27-mm-12315276005001"
soup = BeautifulSoup(requests.get(url).content, "html.parser")
title = soup.title.text.split("|")[0].strip()
description = soup.select_one(".description-content").get_text(strip=True)
price = soup.select_one(".price").text
info = "\n".join(
tag.get_text(strip=True)
for tag in soup.select(
".product-info-details-right .li, .product-info-details-right li"
)
)
print(title)
print()
print(description)
print("-" * 80)
print(price)
print("-" * 80)
print(info)
Prints:
Constellation Quartz 27 mm - 123.15.27.60.05.001
L'esthétique particulièrement remarquable et intemporelle de la collection OMEGA Constellation se caractérise par l'originalité du cadran et la présence des fameuses griffes.Ce modèle brossé se distingue par un cadran en nacre blanche protégé par un verre saphir résistant aux rayures. La lunette sertie de diamants est montée sur un boîtier de 27 mm en acier inoxydable sur un bracelet également en acier inoxydable.Cette montre est animée par le calibre OMEGA 1376, un mouvement de précision à quartz.
--------------------------------------------------------------------------------
5 000,00 €
--------------------------------------------------------------------------------
Diamants
Entre‑corne :18 mm
Bracelet :acier
Boîtier :acier
Diamètre du boîtier :27 mm
Couleur du cadran :blanc
Verre :verre saphir bombé résistant aux rayures, traité antireflet à l’intérieur
Étanchéité :10 bars (100 mètres / 330 pieds)
Type de mouvement :quartz
Calibre :OMEGA 1376
Mouvement de précision à quartz, finition rhodiée.
Durée de vie de la pile :48 mois
Type :quartz
Swiss Made
GARANTIE 5 ANS
Paiement sécurisé
Livraison et retour offerts

Laravel 8 App problem when i try to take data with join

Goodmorning everyone,
As in the title I find myself developing a web application with Laravel where I need to take the data with a join between two tables.
Tables are raccomandata and sap_abilitati where in the raccomandata table the idCliente field is foreign key and refers to the id field of the sap_abilitati table.
When I run the query that I need, without the join, the data is correctly taken from the DB.
But when I do the join, which I think I do correctly, I don't get any results.
Let me explain, to verify that the data taken are grouped correctly (as you can see I used a groupBy), I execute the dd($racc); in the code.
Well, in the case of a query without a join the dd($racc); is executed, while in the case of a query with a join it is not executed.
Do you have any suggestions or advice? I can't understand what this behavior gives
Code without join:
// GESTIONE DELLE SPEDIZIONI
public function gestisciSpedizione(Request $request){
try{
set_time_limit(-1);
//devo recuperare le raccomandate dal DB con isGenerated = 0 e per data e lotto
//prendo la data odierna, devo spedire quelle con data precedente.
$date = date('Y-m-d');
if($request->input('sap') != 'all'){
//dd('Unico Sap');
// qui recupero le raccomandate dello specifico SAP selezionate in fase di prenotazione
//recupero le raccomandate
$racc = Raccomandata::select('*')
->where([
['isGenerated', '=', '0'], //non generate
['created_at', '>', $date.' 00:00:00'], //la data di creazione deve essere precedente la data odierna
['idCliente', '=', $request->input('sap')], //selezioniamo le raccomandate solo per il cliente
])
->get();
//raggruppiamo per idCommessa e cronologico
$racc = $racc->groupBy(['idCommessa', 'cronologico'])->toArray();
dd($racc);
//passo alla creazione dei file
//richiamo la procedura per generare i file .xml
return \App::call('App\Http\Controllers\ExportFileController#exportXML', ['racc'=>$racc, 'all' => '0']);
}
else{
// TODO
}
//loggiamo l'evento e redirectiamo con il messaggio di success dell'operazione
Log::channel('custom_log')->info('L\'utente '.Auth::user().' ha prenotato con successo la spedizione numero: '.$request->input('codice_prenotazione').' FILE :');
return redirect()->back()->with('success', 'Prenotazione della spedizione effettuata con successo');
}catch(\Exception $e){
Log::channel('custom_log')->info('L\'utente '.Auth::user().' non è riuscito a prenotare la spedizione COD:'.$request->input('codice_prenotazione').' ERRORE:'.$e);
return redirect()->back()->with('error', 'Non è stato possibile prenotare la spedizione numero: '.$request->input('codice_prenotazione'));
}
}
code With Join:
// GESTIONE DELLE SPEDIZIONI
public function gestisciSpedizione(Request $request){
try{
set_time_limit(-1);
//devo recuperare le raccomandate dal DB con isGenerated = 0 e per data e lotto
//prendo la data odierna, devo spedire quelle con data precedente.
$date = date('Y-m-d');
if($request->input('sap') != 'all'){
//dd('Unico Sap');
// qui recupero le raccomandate dello specifico SAP selezionate in fase di prenotazione
//recupero le raccomandate
$racc = Raccomandata::select('*', 'sap_abilitati.SAP')
->join('sap_abilitati', 'sap_abilitati.id', '=', 'raccomandata.idCliente')
->where([
['isGenerated', '=', '0'], //non generate
['created_at', '>', $date.' 00:00:00'], //la data di creazione deve essere precedente la data odierna
['idCliente', '=', $request->input('sap')], //selezioniamo le raccomandate solo per il cliente
])
->get();
//raggruppiamo per idCommessa e cronologico
$racc = $racc->groupBy(['sap_abilitati.SAP', 'idCommessa', 'cronologico'])->toArray();
dd($racc);
//passo alla creazione dei file
//richiamo la procedura per generare i file .xml
return \App::call('App\Http\Controllers\ExportFileController#exportXML', ['racc'=>$racc, 'all' => '0']);
}
else{
// TODO
}
//loggiamo l'evento e redirectiamo con il messaggio di success dell'operazione
Log::channel('custom_log')->info('L\'utente '.Auth::user().' ha prenotato con successo la spedizione numero: '.$request->input('codice_prenotazione').' FILE :');
return redirect()->back()->with('success', 'Prenotazione della spedizione effettuata con successo');
}catch(\Exception $e){
Log::channel('custom_log')->info('L\'utente '.Auth::user().' non è riuscito a prenotare la spedizione COD:'.$request->input('codice_prenotazione').' ERRORE:'.$e);
return redirect()->back()->with('error', 'Non è stato possibile prenotare la spedizione numero: '.$request->input('codice_prenotazione'));
}
}

calling a function in powershell then how to reset a function's variable if function calls again itself

My function make a test and if it's true calls again the function
But in this case my variable $label isn't empty.
I need to reset it and don't know how to do that
I was thinking that $label="" can works but it doesn't reset it.
here my code
Function name-label
{
# Incorporate Visual Basic into script
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
# show the Pop Up with the following text.
$label = [Microsoft.VisualBasic.Interaction]::InputBox("Pas plus de 11 caractères`r`n`
1) Que des lettres ou des chifres`
2) Pas de caractères bizarres comme $ * µ %"`
, "Nom de la clef USB", "")
# si plus de 11 caractères
if ($label.length -gt 12)
{
Write-Host "Vous avez mis plus de 11 caractères : $label" -ForegroundColor Red -BackgroundColor Black
$a = new-object -comobject wscript.shell
$intAnswer = $a.popup("Vous avez tapé ce nom $label qui est trop long pour la clé USB`r `n Pas plus de 11 caractères`r `n Nouvel essai !",0,"ERREUR !",0)
name-label # Restart function
}
}
Recursively calling Name-Label is completely unnecessary, you can do this with a simple do{}until() loop:
Function Name-Label
{
# Import Visual Basic into script
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$firstRun = $true
# show the Pop Up with the following text.
do{
if(-not $firstRun){
# loop running again, must have failed input validation
$null = (New-Object -ComObject WScript.Shell).Popup("Vous avez tapé ce nom $label qui est trop long pour la clé USB`r `n Pas plus de 11 caractères`r `n Nouvel essai !",0,"ERREUR !",0)
}
$firstRun = $false
# prompt user for label
$label = [Microsoft.VisualBasic.Interaction]::InputBox("Pas plus de 11 caractères`r`n`
1) Que des lettres ou des chifres`
2) Pas de caractères bizarres comme $ * µ %",
"Nom de la clef USB", "")
} until ($label -match '^[\d\p{L}]{1,11}$')
return $label
}
The regex pattern used for input validation is as follows:
^[\d\p{L}]{1,11}$
^ # start of string
[
\d # digits
\p{L} # Letters
]
{1,11} # between 1 and 11 of the previous character class
$ # end of string

Eloquent InnoDB cannot add foreign key (error 1215)

I am trying to create a table with foreign keys with eloquent ORM and InnoDB engine and it is failing with error :
General error: 1215 Cannot add external index constraint.
The thing is that it works on mariaDB, i tried on an other computer.
This is the table :
DB::schema()->create('client', function($table){
$table->engine = 'InnoDB';
$table->increments('id')
->comment('Identifiant du client');
$table->string('cli_nom', 25)
->comment('Nom ou raison sociale du client');
$table->string('cli_activite', 5)
->comment('Code NAF activité');
$table->text('cli_activite_desc')
->comment('Description du code NAF');
$table->integer('cli_adresse_id')
->unsigned()
->comment('Id de l adresse du client');
$table->integer('cli_type')
->comment('1:client ou 0:prospect');
$table->integer('cli_theme_couleur_id')
->unsigned()
->comment('Id de la couleur de personnalisation d interface');
$table->integer('cli_theme_id')
->unsigned()
->comment('Id du theme acheté par le client');
$table->timestamps();
$table->foreign('cli_adresse_id')
->references('id')->on('adresse')
->onDelete('restrict');
$table->foreign('cli_theme_couleur_id')
->references('id')->on('theme_couleur')
->onDelete('restrict');
$table->foreign('cli_theme_id')
->references('id')->on('theme')
->onDelete('restrict');
});
I also tried to add index() to the fk:
$table->integer('cli_adresse_id')
->unsigned()
->index()
->comment('Id de l adresse du client');
EDIT
This is the referenced table :
DB::schema()->create('adresse', function($table){
$table->increments('id')
->unsigned()
->comment('Identifiant de l adresse');
$table->integer('adr_num')
->comment('Numéro de rue');
$table->string('adr_voie', 250)
->comment('Rue ou voie dans la ville');
$table->string('adr_cp', 10)
->comment('Code postal de l adresse');
$table->string('adr_ville', 250)
->comment('Nom de la ville de l adresse');
$table->integer('adr_pays')
->comment('Identifiant du pays');
$table->timestamps();
});

responseAsSlurper error groovy

im having problems trying to encapsulate this sentence in to a groovy function.
-----------------------------------mi call-------------------------------
sizeOfferPrices =
responseAsSlurper.Body.FlightPriceRS.PricedFlightOffers.PricedFlightOffer.OfferPrice.size();
offerAmount = getTotalPrice(sizeOfferPrices)
-----------------------------my function--------------------------------
def getTotalPrice (sizeOfferPrices){
def strTravelersAssociated
def floatImporteViaje = 0
String [] arrTravelersAssociated
def offerAmountTemp
//recorremos los precios que se nos ha devuelto en la oferta
for(i=0; i<=sizeOfferPrices-1; i++){
//obtenemos el precio
offerAmountTemp = responseAsSlurper.Body.FlightPriceRS.PricedFlightOffers.PricedFlightOffer.OfferPrice[i].RequestedDate.PriceDetail.TotalAmount.SimpleCurrencyPrice
offerAmountTemp = offerAmountTemp.toFloat();
//obtenemos los datos de los viajeros asociados , casteamos a string y splitamos para obtener array
strTravelersAssociated = responseAsSlurper.Body.FlightPriceRS.PricedFlightOffers.PricedFlightOffer.OfferPrice[i].RequestedDate.Associations.AssociatedTraveler.TravelerReferences
strTravelersAssociated = strTravelersAssociated.toString();
arrTravelersAssociated = strTravelersAssociated.tokenize(" ");
//obtenemos el numero de viajeros por oferta
intTravelersByOffer = arrTravelersAssociated.size().toInteger();
//realizamos la multiplicaciónd viajeros por su oferta asociada
floatImporteViajeTemp = (offerAmountTemp * intTravelersByOffer).round(2);
floatImporteViaje = floatImporteViaje + floatImporteViajeTemp;
}
//obtenemos el precio total
amount = floatImporteViaje.round(2);
return amount
}
_________________________ERROR_________________________________________
groovy.lang.MissingPropertyException: no such Property
resposeAsSpluger
any suggestions? thanks a lot.
The error is unrelated to the function you've posted, because it's occurring before the function is called. Here's the code where you attempt to call the function
sizeOfferPrices = responseAsSlurper.Body.FlightPriceRS.PricedFlightOffers.PricedFlightOffer.OfferPrice.size();
offerAmount = getTotalPrice(sizeOfferPrices)
The error occurs on the first line (before getTotalPrice is called) because you try to access a property responseAsSlurper which does not exist.