-1
I have the following problem, when trying to implement a consultation with joins, in query Builder:
My Query (pure SQL):
SELECT COUNT(*) as total,
orgao.sigla AS sigla_org_uni
FROM protocolo
INNER JOIN procedimento p ON protocolo.id_protocolo = p.id_procedimento
INNER JOIN unidade uni_ger
INNER JOIN orgao ON uni_ger.id_orgao = orgao.id_orgao
ON protocolo.id_unidade_geradora = uni_ger.id_unidade
WHERE protocolo.sta_protocolo='P'
AND protocolo.sta_nivel_acesso_global<>'2'
GROUP BY uni_ger.id_orgao, orgao.sigla
ORDER BY orgao.sigla ASC
My query with Query Builder:
DB::select(`orgao.sigla as sigla_org_uni`)
->addSelect(DB::raw(`COUNT(*) as total`))
->from(`protocolo`)
->join(`procedimento as p`, function($join) {
$join->on(`protocolo.id_protocolo`, `=`, `p.id_procedimento`);
})
->from(`unidade as uni_ger`)
->join(`orgao`, function($join) {
$join->on(`protocolo.id_unidade_geradora`, `=`, `uni_ger.id_unidade`);
})
->where(`protocolo.sta_protocolo`, `=`, `P`)
->where(`protocolo.sta_nivel_acesso_global`, `<>`, 2)
->groupBy(`uni_ger.id_orgao`)
->groupBy(`orgao.sigla`)
->orderBy(`orgao.sigla`, `ASC`)
->get();
I’m pretty sure the query inside the Uilder query is correct, but when I call it inside the application, Laravel returns the following error:
SQLSTATE[HY000]: General error: 20018 Invalid object name 'procedimento'.
[20018] (severity 16) [(null)] (SQL: select [orgao].[sigla] as
[sigla_org_uni], COUNT(*) as total from [unidade] as [uni_ger] inner join
[procedimento] as [p] on [protocolo].[id_protocolo] = [p].[id_procedimento]
inner join [orgao] on [protocolo].[id_unidade_geradora] = [uni_ger].
[id_unidade] where [protocolo].[sta_protocolo] = P and [protocolo].
[sta_nivel_acesso_global] <> 2 group by [uni_ger].[id_orgao], [orgao].
[sigla] order by [orgao].[sigla] asc)
Just look at your SQL so
INNER JOIN unidade uni_ger
and in Builder it’s like this->from(
unit as uni_ger)
, it seems that there is something wrong there! take a look! and it seems that in SQL already has problems– novic
here’s another problem
->where(
protocol.sta_protocol,
=,
P)
because if it is a string of that letter then it is single (or double) quotes example->where(
protocol.sta_protocol,
=, 'P')
, that is, your code has problems in SQL and Builder– novic
It is! this case is quite peculiar, considering that I have not found any example to implement a Join in the query Builder in which there is no 'ON'. For example, I would like to know how to convert pure sql (INNER JOIN uni_ger drive) to Query Builder. I believe this is the source of the problem here. Thanks in advance for the feedback @Virgilionovic !
– Renato Rodrigues
If you put the
SQL
right I make an answer with her, is that in one of the Ner Join is missing ! take a look there– novic