I'm having the following problem, when trying to implement a query with joins, in the 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 that the query inside the query builder is correct, however 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)