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

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'));
}
}

Related

How to write single CSV file using pyspark in Databricks

Good morning all!!
Yesterday I was looking for a function that was able to write a single file CSV with pyspark in Azure Databricks but I did not find anything. So I've built my own function and I wanted to share my solution with the community and if it's possible create like a thread with different solutions for the same problem.
Sorry, because I commented the code in Spanish but basically the function does:
Save the dataframe you've created into a new directory (which is allocated inside the path you've defined and begin with 'temp_') and save the partition there using "coalesce(1)"
Rename the CSV file as you want and moves it to the desired path
Delete de temporary file
That's all! You have your unique CSV file
def escribe_fichero_unico(dataframe, path, file_name, file_format = 'csv'):
"""
Definición: (1) Genera carpeta temporal para guardar particiones que Spark genera por defecto
a la hora de guardar archivos, (2) Une todas las particiones en un único archivo, (3) Mueve este
archivo al directorio anterior y (4) Borra la carpeta temporal
Parámetros:
dataframe: dataframe que quieras guardar como fichero único
file_name: en formato string escribe nombre del archivo
file_format: en formato string escribe 'csv' o 'parquet'
path: en formato string escribe el path donde quieres guardar el csv
"""
import os
# 1) Guardamos el dataframe creando una carpeta temporal que guarda todas las particiones
path_temp = path + 'temp_' + file_name + '_trash'
if file_format == 'csv':
dataframe.coalesce(1).write.format('csv').mode('overwrite') \
.options(header="true", schema="true", delimiter=";") \
.save(path_temp)
else if file_format == 'parquet':
dataframe.coalesce(1).write.format("parquet").mode("overwrite") \
.save(path_temp)
# 2)Une todas las particiones en un único archivo
file_part = [file.path for file in dbutils.fs.ls(path_temp) if os.path.basename(file.path).startswith('part')][0]
# 3) Mueve este archivo al directorio anterior
dbutils.fs.mv(file_part, path + file_name + '.' + file_format)
# 4) Borra la carpeta temporal
dbutils.fs.rm(path_temp, True)
I hope this work for you as well :)

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

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 ?

Loading data with JSON.parse: Unexpected token /

I'm pretty new with this JSON and AJAX staff, so I was following a tutorial on youtube: https://www.youtube.com/watch?v=rJesac0_Ftw&t=1029s.
The thing is that I have followed the steps exactly like in the video, but I get the following error:
VM34:1 Uncaught SyntaxError: Unexpected token / in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.theRequest.onload (loader.js:5)
My JSON script:
[
{
"name":"一",
"sound": {
"kunyomi": ["ひと.つ"],
"onyomi": ["イチ"]
},
"description":"Representaba la unidad, el absoluto. Cuando funciona como componente, este carácter adquiere el significado de suelo o de techo según su posición: si se encuentra encima de otro componente, toma el significado de techo; si está debajo, de suelo. Todas las formas antiguas de los números están asociadas a fuerzas del universo y a la mitología. Los números pares son el ying y los impares son el yang.",
"examples":["-月[いちがつ] - Enero", "-日[ついたち] - Día uno", "-回[いっかい] - Dos veces", "-階[いっかい] - Primer Piso"]
},
{
"name":"ニ",
"sound": {
"kunyomi": ["ふた.つ"],
"onyomi": ["ニ、ジ"]
},
"description":"Representa el cielo 一 y la tierra 一, el ying y el yang. Al igual que en el caso de los numerales romanos, el kanji de dos es una simple duplicación del trazo horizontal que significa uno.",
"examples":["二月[にがつ] - Febrero", "二日[ふつか] - Día dos", "二回[にかい] - Dos veces"]
}
]
And I call that JSON with the following code:
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://127.0.0.1/japones_flat/kanjis_n5.json');
ourRequest.onload = function() {
"use strict";
var response = JSON.parse(ourRequest.responseText);
console.log(response[0]);
};
ourRequest.send();
I made a little research and it looks like the problem resides in the JSON.parse method, saying that the token "/" is making troubles. After that, I noticed that Dreamweaver had left by default a comment in my .json file, so I deleted it (Because it started with "/") but I keep getting this anoying error. Can you guys help me?
Thanks in advance!

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.

QSqlError("", "Parameter count mismatch", "")

Sorry for my English. I'm trying to select some data from a database table in order to insert the into a table from another database.
This is my code:
void Partes::Guardar_Solicitud()
{
hospital=QSqlDatabase::addDatabase("QSQLITE");
hospital.setDatabaseName("C:/Sqlite3/Hospital.sqlite");
if(hospital.open()){
qDebug()<<"8.Se ha conectado a la base de datos Hospital";
}else{
qDebug()<<"8.ERROR. No se ha conectado a la base de datos Hospital";
}
QSqlQuery seleccionar;
seleccionar.prepare("SELECT*FROM Partes WHERE N_Parte=:ID");
seleccionar.bindValue(":ID",ui->lineEditN_Parte->text());
if(seleccionar.exec())
{
qDebug()<<"9.Los datos del parte se han seleccionado correctamente";
}else{
qDebug()<<"9.ERROR. Los datos del parte no se han seleccionado correctamente";
qDebug()<<"9.ERROR:"<<seleccionar.lastError();
}
seleccionar.next();
QString _N_Solicitud = seleccionar.value(0).toByteArray().constData();
QString _Fecha_Emision = seleccionar.value(1).toByteArray().constData();
QString _Codigo_Equipo = seleccionar.value(2).toByteArray().constData();
QString _Equipo = seleccionar.value(3).toByteArray().constData();
QString _Marca = seleccionar.value(9).toByteArray().constData();
QString _Modelo = seleccionar.value(10).toByteArray().constData();
QString _N_Serie = seleccionar.value(11).toByteArray().constData();
QString _Localizacion = seleccionar.value(6).toByteArray().constData();
QString _Descripcion_Solicitud = seleccionar.value(19).toByteArray().constData();
empresa=QSqlDatabase::addDatabase("QSQLITE");
empresa.setDatabaseName("C:/Sqlite3/Empresa.sqlite");
if(empresa.open()){
qDebug()<<"10.Se ha conectado a la base de datos Empresa";
}else{
qDebug()<<"10.ERROR. No se ha conectado a la base de datos Empresa";
}
QSqlQuery seleccionar2;
seleccionar2.prepare("SELECT*FROM Tecnicos WHERE Nombre_Usuario='a' and Contraseña='7'");
if(seleccionar2.exec())
{
qDebug()<<"11.Los datos del usuario se han seleccionado correctamente";
}else{
qDebug()<<"11.ERROR. Los datos del usuario no se han seleccionado correctamente";
qDebug()<<"11.ERROR:"<<seleccionar2.lastError();
}
seleccionar2.next();
QString _Unidad_Hospitalaria = seleccionar2.value(5).toByteArray().constData();
QString _Unidad_Tecnica = seleccionar2.value(6).toByteArray().constData();
QString _Peticionario = seleccionar2.value(0).toByteArray().constData();
QString _Telefono = seleccionar2.value(8).toByteArray().constData();
QString _Tecnico_Asignado = seleccionar2.value(0).toByteArray().constData();
QString _Estado_Solicitud = seleccionar2.value(7).toByteArray().constData();
QSqlQuery guardar_s;
guardar_s.prepare("INSERT INTO Solicitudes_Trabajo (N_Solicitud, Fecha_Emision, Unidad_Hospitalaria,"
"Codigo_Equipo, Equipo, Marca)"
"VALUES (:N_Solicitud, :Fecha_Emision, :Unidad_Hospitalaria, :Codigo_Equipo, :Equipo,"
":Marca)");
guardar_s.bindValue(":N_Solicitud", _N_Solicitud);
guardar_s.bindValue(":Fecha_Emision", _Fecha_Emision);
guardar_s.bindValue(":Unidad_Hospitalaria", _Unidad_Hospitalaria);
guardar_s.bindValue(":Codigo_Equipo", _Codigo_Equipo);
guardar_s.bindValue(":Equipo", _Equipo);
guardar_s.bindValue(":Marca", _Marca);
if(guardar_s.exec( ))
{
ui->label_Guardar->setText("Solicitud guardada correctamente");
qDebug()<<"12.Los datos del parte se han guardado en la Solicitud de Trabajo";
}
else
{
ui->label_Guardar->setText("La solicitud no se ha guardado correctamente");
qDebug()<<"12.ERROR. Los datos del parte no se han guardado en la Solicitud de Trabajo";
qDebug()<<"12.ERROR:"<<guardar_s.lastError();
}
}
Table "Partes" belongs to the "Hospital" database.
Table "Solicitudes_Trabajo" belongs to the "Empresa" database.
This code works fine, and inserts the values into the table perfectly. But when I add more values to be inserted there appears a QSqlError.
This is the INSERT INTO code that doesn't work:
QSqlQuery guardar_s;
guardar_s.prepare("INSERT INTO Solicitudes_Trabajo (N_Solicitud, Fecha_Emision, Unidad_Hospitalaria, Codigo_Equipo,"
"Equipo, Marca, Modelo, N_Serie, Localizacion, Unidad_Tecnica, Peticionario, Telefono, "
"Descripcion_Solicitud, Tecnico_Asignado, Tipo_Solicitud, Estado_Solicitud) "
"VALUES (:N_Solicitud, :Fecha_Emision, :Unidad_Hospitalaria, :Codigo_Equipo, :Equipo, :Marca, :Modelo,"
":N_Serie, :Localizacion, :Unidad_Tecnica, :Peticionario, :Telefono, :Descripcion_Solicitud,"
":Tecnico_Asignado, :Tipo_Solicitud, :Estado_Solicitud)");
guardar_s.bindValue(":N_Solicitud", _N_Solicitud);
guardar_s.bindValue(":Fecha_Emision", _Fecha_Emision);
guardar_s.bindValue(":Unidad_Hospitalaria",_Unidad_Hospitalaria);
guardar_s.bindValue(":Codigo_Equipo", _Codigo_Equipo);
guardar_s.bindValue(":Equipo", _Equipo);
guardar_s.bindValue(":Marca", _Marca);
guardar_s.bindValue(":Modelo", _Modelo);
guardar_s.bindValue(":N_Serie", _N_Serie);
guardar_s.bindValue(":Localizacion", _Localizacion);
guardar_s.bindValue(":Unidad_Tecnica", _Unidad_Tecnica);
guardar_s.bindValue(":Peticionario", _Peticionario);
guardar_s.bindValue(":Telefono", _Telefono);
guardar_s.bindValue(":Descripcion_Solicitud", _Descripcion_Solicitud);
guardar_s.bindValue(":Tecnico_Asignado", _Tecnico_Asignado);
guardar_s.bindValue(":Tipo_Solicitud", "a");
guardar_s.bindValue(":Estado_Solicitud", _Estado_Solicitud);
QDebug:
7.Los datos del usuario se han mostrado correctamente
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
8.Se ha conectado a la base de datos Hospital
9.Los datos del parte se han seleccionado correctamente
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
10.Se ha conectado a la base de datos Empresa
11.Los datos del usuario se han seleccionado correctamente
12.ERROR. Los datos del parte no se han guardado en la Solicitud de Trabajo
12.ERROR: QSqlError("", "Parameter count mismatch", "")
Are these too much data to insert for Qt Creator? Why it is able to insert 6 values but it isn't able to insert 16 values?
Thanks for replying!
At the end it was a typo. I was trying to insert a value into a column called Localización by using:
guardar_s.prepare("INSERT INTO Solicitudes_Trabajo (Localizacion)
The problem is in the accent mark.