2
Hello, I am using Laravel 5.6 and I am creating a query using eloquent Laravel, however I am having difficulty creating a subquery
what I want to create is simple in SQL server:
,DT_ALTA = (SELECT TOP(1)
DH_DESOSPITALIZACAO
FROM
TB_CAPTA_EVO_STATUS_CAES AS CAES
WHERE
(CAES.ID_CD_INTERNACAO = CAIN.ID_CD_INTERNACAO
AND FL_DESOSPITALIZACAO IN (4, 5, 6, 16, 19) )
OR (CAES.ID_CD_INTERNACAO = CAIN.ID_CD_INTERNACAO
AND FL_FINALIZACAO = 'S')
ORDER BY CAES.DH_DESOSPITALIZACAO DESC)
However via Eloquent I’m having difficulties, follow my query:
$mot = db::table('TB_CAPTA_INTERNACAO_CAIN as CAIN')
->join('TB_CRM_PESSOAS_CRMP as CRMP','CAIN.ID_CD_PACIENTE','=','CRMP.ID_CD_PESSOA')
->join('TB_CAPTA_CFG_ORIGEM_CAGO as CAGO','CAIN.ID_CD_ORIGEM','=','CAGO.ID_CD_ORIGEM')
->join('TB_CRM_PACIENTES_CRPC as CRPC','CRMP.ID_CD_PESSOA','=','CRPC.ID_CD_PESSOA')
//->join('TB_CAPTA_EVO_STATUS_CAES as CAES','CAES.ID_CD_INTERNACAO','=','CAIN.ID_CD_INTERNACAO')
->select('CAIN.ID_CD_INTERNACAO','CAIN.DH_ADMISSAO_HOSP','CAIN.DH_INICIO_ACOMPANHAMENTO','CRMP.NM_PESSOA','CRMP.NM_SOBRENOME','CAGO.DS_TITULO','CRPC.NR_CREDENCIAL','CRMP.DH_NASCIMENTO','CRMP.ID_CD_PESSOA')
->where('IN_SITUACAO',$request->get('situacao'));
If anyone can help me I appreciate it from now on.
I got it solved, follow the resolution code:
->addSelect(db::raw("(SELECT TOP 1 CAES.DH_DESOSPITALIZACAO FROM TB_CAPTA_EVO_STATUS_CAES as CAES WHERE CAES.ID_CD_INTERNACAO = CAIN.ID_CD_INTERNACAO) as DH_DESOSPITALIZACAO" ))
I added this passage in eloquent, it makes the subquery right.
Puts your entire query. It looks like it’s half done.
– Diego Souza
Do you say the SQL server or eloquent query? The SQL server is a very big project, and the Eloquent one doesn’t have much more, just order by etc
– André Tripode Colognesi