I want to convert this SQL Query to LAravel SQL Builder but i don't know why I already read the laravel documentation but I can't find the answer
SQL Query:
SELECT
CONTRATO,
CASE WHEN RAZONSOCIAL IS NULL OR RAZONSOCIAL = ''
THEN ISNULL(PATERNO, '') + ' ' + ISNULL(MATERNO, '') + ' ' + ISNULL(NOMBRES, '')
ELSE RAZONSOCIAL
END AS NOMBRE,
CADENAUNICA,
CLAVERASTREO,
FECHAASIENTO,
IDGARANTIA,
RutaGuardadoPDF,
RutaGuardadoXML
FROM
DEUDORES AS D
LEFT JOIN
RELACIONES AS R
ON D.RUGID = R.RUGID
WHERE CONTRATO = 'A1412015'
AND D.AcreedorId IN (
SELECT
ACREEDORID
FROM
[MasterCLI].[dbo].[Rrug]
WHERE FIDEICOMISOID = 5
)
and i do this code in laravel
$AcreedorFide = \DB::connection('sqlsrv')
->table('Rrug')
->select('AcreedorID')
->where('Fideicomiso', $fideicomiso)
->get();
$BoletaRUG = \DB::connection('RUG')
->table('Deudores')
->select(
'Contrato',
'CadenaUnica',
'ClaveRastreo',
'FechaAsiento',
'IdGarantia',
'RutaGuardadoPDF',
'RutaGuardadoXML'
)
->select(DB::raw('CASE WHEN RAZONSOCIAL IS NULL'))
->leftJoin('Relaciones','Deudores.RugId', '=', 'Relaciones.RugId')
->where('Contrato', $Contrato)
->wherein('Acreedorid', $AcreedorFide)
->get();
The most SQL-like way of remaking this query in the Query Builder is the following:
For anyone stuck on translating queries, as the comments have stated, the easiest way to remake large, complex-looking queries in the builder is by dumping the query using
->toSql()
instead of->get()
and checking if it's missing something or not. Trial and error.My personal advice is to start from the subqueries and work your way up. Also, Some differences/shorthands:
DB::connection(...)->query()->select(...)->from('DEUDORES', 'D')->where(...)
,you can specify the main table you're querying first:
DB::connection(...)->table('DEUDORES', 'D')->select(...)->where(...)
'='
you can leave it implied. In this example:leftJoin('RELACIONES AS R', 'D.RUGID', '=', 'R.RUGID')
becomes
leftJoin('RELACIONES AS R', 'D.RUGID', 'R.RUGID')
where('CONTRATO', '=', 'A1412015')
becomeswhere('CONTRATO', 'A1412015')
DB_CONNECTION
in your.env
file), you can skip theconnection(...)
in the queries.DB::connection(...)->table(...)
becomesDB::table(...)
.