Introdução
A classe DAO, acrônomo para Data Access Objects / Objetos de Acesso a Dados, é uma classe NFS criada para abstrair o acesso aos dados do NFS que visa simplificar, padronizar, dar clareza e agilizar o desenvolvimento de EntryPoints em PHP. Seu uso é fortemente indicado para manter a integridade e a evolução constante do Framework NFS.
Alguns exemplos
// Obtem lista de registros (array)
$lista = Dao::table('EQP')->get();
// Obtem lista de registros ativos
$listaSomenteAtivos = Dao::table('EQP')->enables()->get();
// Obtem lista de registros inativos
$listaSomenteInativos = Dao::table('EQP')->disables()->get();
// Obtem lista de registros (ativos e inativos)
$listaAtivosEInativos = Dao::table('EQP')->all()->get();
// Obter dados de um registro com seus relacionamentos padrões (trazendo as _FK)
$dadosDoEquipamento = Dao::table('EQP')->seqDb(345);
// modo lazy (sem relacionamentos)
Dao::table('EQP')->seqDb(14, true);
// ou
Dao::table('EQP')->lazy()->seqDb(14, true);
// Se precisar só de um campo da tabela (só funciona em modo lazy):
$descricaoEquipamento = Dao::table('EQP')->select(['DESCRICAO'])->seqDb(14, true);
/*
* Obter lista de registros agrupados por SEQ_DB
* (usado com frequência em buscas e for's / montagem de EntryPoint / Relatórios)
*/
$rows = Dao::table('equipamento')
->orderBy('DESCRICAO','DESC')
->groupBy('SEQ_DB')
->toArray()
->get();
Métodos Básicos / Padrões
table
/**
* Alias para Dao::from(), só que chamado estaticamente
*
* @param string $table Nome da tabela
* @param string $alias Apelido da tabela (será usado o nome da tabela se for nulo)
*
* @return $this
*/
table($table, $alias = null): self
from
/**
* Origem dos dados da query (sem prefixo APP_)
* ::from('table', 'alias')
*
* @param string $table Nome da tabela
* @param string $alias Apelido da tabela (será usado o nome da tabela se for nulo)
*
* @return $this
*/
from($table, $alias): self
select
/**
* Colunas da Query
* ::select(['col1', 'col2', n])
* ::select('col1', 'col2')
* ::select('*')
*
* @param mixed $fields
*
* @return $this
*/
select($fields): self
Exemplo:
$boletins = Dao::table('boletim')
->select('seq_db', 'empresa', 'filial', 'local', 'ini_dh', 'fim_dh')
->orderBy('filial', 'asc')
->limit(5)
->get();
echo '<pre>';
print_r($boletins);
echo '</pre>';
get()
/**
* Executa query e retorna registros
*
* @return array
*/
get(): array
Exemplo get()
$boletins = Dao::table('boletim')->get();
echo '<pre>';
print_r($boletins);
echo '</pre>';
first()
/**
* Executa query e retorna primeiro registro
* de acordo com orderBy
*
* @return array
*/
first(): array
Exemplo first()
$boletins = Dao::table('boletim')->first();
echo '<pre>';
print_r($boletins);
echo '</pre>';
Métodos de Junção
innerJoin
/**
* Registra inner join à consulta
*
* @param string $fromAlias
* @param string $table
* @param string $joinAlias
* @param string $condition
*
* @return $this
*/
innerJoin($fromAlias, $table, $joinAlias, $condition): self
Exemplo innerJoin
$dados = Dao::table('apontamento', 'ap')
->select([
'ap.seq_db as apontamento_seq_sb',
'cli.descricao',
'cli.loja',
'cli.endereco',
'est.descricao as estado',
'est.sigla'
])
->innerJoin('ap', 'cliente', 'cli', 'cli.seq_db = ap.cliente_seq_db')
->innerJoin('cli', 'estado', 'est', 'est.seq_db = cli.estado_seq_db')
->orderBy('cli.descricao', 'asc')
->get();
echo '<pre>';
print_r($dados);
echo '</pre>';
leftJoin
/**
* Registra left join à consulta
*
* @param string $fromAlias
* @param string $table
* @param string $joinAlias
* @param string $condition
*
* @return $this
*/
leftJoin($fromAlias, $table, $joinAlias, $condition): self
Exemplo leftJoin
$boletins = Dao::table('boletim', 'b')
->select([
'b.seq_db boletim_seq_db',
'b.empresa',
'b.filial',
'b.local',
'b.ini_dh',
'b.fim_dh',
'a.seq_db as apontamento_seq_sb',
'd.km_inicial',
'd.km_final',
])
->innerJoin('b', 'apontamento', 'a', 'a.seq_db_device_master_seq_db = b.seq_db')
->leftJoin('a', 'apontamento_deslocamento', 'd', 'd.apontamento_seq_db = a.seq_db')
->orderBy('b.seq_db', 'desc')
->get();
echo '<pre>';
print_r($boletins);
echo '</pre>';
rightJoin
/**
* Registra right join à consulta
*
* @param string $fromAlias
* @param string $table
* @param string $joinAlias
* @param string $condition
*
* @return $this
*/
rightJoin($fromAlias, $table, $joinAlias, $condition): self
Exemplo rightJoin
$boletins = Dao::table('boletim', 'b')
->select([
'b.seq_db boletim_seq_db',
'b.empresa',
'b.filial',
'b.local',
'b.ini_dh',
'b.fim_dh',
'a.seq_db as apontamento_seq_sb',
'd.km_inicial',
'd.km_final'
])
->innerJoin('b', 'apontamento', 'a', 'a.seq_db_device_master_seq_db = b.seq_db')
->rightJoin('a', 'apontamento_deslocamento', 'd', 'd.apontamento_seq_db = a.seq_db')
->orderBy('b.seq_db', 'desc')
->todos()
->get();
echo '<pre>';
print_r($boletins);
echo '</pre>';
Métodos de Filtro
where
/**
* Adiciona filtro igual (where x = y) com operador lógico AND
* ::where(['key' => $value, n])
* ::where(['a' => ':a', 'ab' => ':ab', n])
*
* @param array $condition
*
* @return $this
*/
where(array $conditions, $type = 'AND'): self
Exemplo where
$eqps = Dao::table('apontamento_equipamento', 'ae')
->where([
'ae.CLIENTE_SEQ_DB' => 1396,
])
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
orWhere
/**
* Alias para adiciona filtro igual (where x = y) com operador lógico OR
* ::where(['a' => 'b', 'ab' => '3', n])
* ::where(['a' => ':a', 'ab' => ':ab', n])
*
* @param array $condition
*
* @return $this
*/
orWhere(array $conditions): self
Exemplo orWhere
$eqps = Dao::table('apontamento_equipamento', 'ae')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->orWhere(['ae.CLIENTE_SEQ_DB' => 98])
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereDiff
/**
* Adiciona filtro Diferente (where x <> y) e especifica operador lógico
*
* @param string $key Coluna da condição
* @param mixed $value Valor
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereDiff($key, $value, $type = 'AND')
Exemplo whereDiff
$eqps = Dao::table('apontamento_equipamento', 'ae')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereDiff('SEQ_DB_DEVICE', '1548159687880')
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereGreaterThan
/**
* Adiciona filtro maior que (where x > y) e especifica operador lógico
*
* @param string $key Coluna da condição
* @param mixed $value Valor
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereGreaterThan($key, $value, $type = 'AND')
Exemplo whereGreaterThan
$eqps = Dao::table('apontamento_equipamento', 'ae')
->select('ae.SEQ_DB', 'ae.CLIENTE_SEQ_DB', 'ae.FUNCIONARIO_SEQ_DB', 'ae.HORIMETRO')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereGreaterThan('HORIMETRO', 125)
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>'/
whereGreaterEqualsThan
/**
* Adiciona filtro maior ou igual a (where x >= y) e especifica operador lógico
*
* @param string $key Coluna da condição
* @param mixed $value Valor
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereGreaterEqualsThan($key, $value, $type = 'AND')
Exemplo whereGreaterEqualsThan
$eqps = Dao::table('apontamento_equipamento', 'ae')
->select('ae.SEQ_DB', 'ae.CLIENTE_SEQ_DB', 'ae.FUNCIONARIO_SEQ_DB', 'ae.HORIMETRO')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereGreaterEqualsThan('HORIMETRO', 125)
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereLessThan
/**
* Adiciona filtro meno que (where x < y) e especifica operador lógico
*
* @param string $key Coluna da condição
* @param string $value Valor
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereLessThan($key, $value, $type = 'AND')
Exemplo whereLessThan
$eqps = Dao::table('apontamento_equipamento', 'ae')
->select('ae.SEQ_DB', 'ae.CLIENTE_SEQ_DB', 'ae.FUNCIONARIO_SEQ_DB', 'ae.HORIMETRO')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereLessThan('HORIMETRO', 125)
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereLessEqualsThan
/**
* Adiciona filtro menor ou igual a (where x <= y) e especifica operador lógico
*
* @param string $key Coluna da condição
* @param string $value Valor
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereLessEqualsThan($key, $value, $type = 'AND')
Exemplo whereLessEqualsThan
$eqps = Dao::table('apontamento_equipamento', 'ae')
->select('ae.SEQ_DB', 'ae.CLIENTE_SEQ_DB', 'ae.FUNCIONARIO_SEQ_DB', 'ae.HORIMETRO')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereLessEqualsThan('HORIMETRO', 125)
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereIn
/**
* Adiciona filtro entre valores (where x in (a,b,c)) e especifica operador lógico
*
* @param string $key Coluna da condição
* @param string|array $value Valor ou lista de valores
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereIn($key, $value, $type = 'AND')
Exemplo whereIn
$eqps = Dao::table('apontamento_equipamento', 'ae')
->select('ae.SEQ_DB', 'ae.CLIENTE_SEQ_DB', 'ae.FUNCIONARIO_SEQ_DB', 'ae.HORIMETRO')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereIn('HORIMETRO', [125, 123])
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereNotIn
/**
* Adiciona filtro não entre valores que (where x not in (a,b,c)) e especifica operador lógico
*
* @param string $key Coluna da condição
* @param string|array $value Valor ou lista de valores
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereNotIn($key, $value, $type = 'AND')
Exemplo whereNotIn
$eqps = Dao::table('apontamento_equipamento', 'ae')
->select('ae.SEQ_DB', 'ae.CLIENTE_SEQ_DB', 'ae.FUNCIONARIO_SEQ_DB', 'ae.HORIMETRO')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereNotIn('HORIMETRO', '125, 123')
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereIsNull
/**
* Adiciona filtro é nulo (where x is null) e especifica operador lógico
*
* @param string $key Coluna da condição
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereIsNull($key, $type = 'AND')
Exemplo whereIsNull
$eqps = Dao::table('apontamento', 'ae')
->select('ae.SEQ_DB', 'ae.FUNCIONARIO_SEQ_DB', 'ae.FIM_DH')
->where(['ae.FUNCIONARIO_SEQ_DB' => 849])
->whereIsNull('ae.FIM_DH')
->limit(10)
->orderBy('INS_DH', 'DESC')
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereIsNotNull
/**
* Adiciona filtro não é nulo (where x > y) e especifica operador lógico
*
* @param string $key Coluna da condição
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereIsNotNull($key, $type = 'AND')
Exemplo whereIsNotNull
$eqps = Dao::table('apontamento', 'ae')
->select('ae.SEQ_DB', 'ae.FUNCIONARIO_SEQ_DB', 'ae.FIM_DH')
->where(['ae.FUNCIONARIO_SEQ_DB' => 849])
->whereIsNotNull('ae.FIM_DH')
->limit(10)
->orderBy('INS_DH', 'DESC')
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereLike
/**
* Adiciona condição Like
*
* @param string $key Coluna da condição
* @param mixed $value Valor de filtro
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereLike($key, $value, $type = 'AND')
Exemplo whereLike
$eqps = Dao::table('cliente', 'cli')
->select('cli.SEQ_DB', 'cli.DESCRICAO', 'cli.BAIRRO')
->whereLike('cli.BAIRRO', 'RURAL')
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereStartsWith
/**
* Adiciona condição Like que começa com o valor especificado
*
* @param string $key Coluna da condição
* @param mixed $value Valor de filtro
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereStartsWith($key, $value, $type = 'AND')
Exemplo whereStartsWith
$eqps = Dao::table('cliente', 'cli')
->select('cli.SEQ_DB', 'cli.DESCRICAO', 'cli.BAIRRO')
->whereStartsWith('cli.BAIRRO', 'RURAL')
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereEndsWith
/**
* Adiciona condição Like que termina com o valor especificado
*
* @param string $key Coluna da condição
* @param mixed $value Valor de filtro
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereEndsWith($key, $value, $type = 'AND')
Exemplo whereEndsWith
$eqps = Dao::table('cliente', 'cli')
->select('cli.SEQ_DB', 'cli.DESCRICAO', 'cli.BAIRRO')
->whereEndsWith('cli.BAIRRO', 'RURAL')
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereBetween
/**
* Adiciona condição por range de dois valores
*
* @param string $key Coluna da condição
* @param mixed $ini Valor inicial
* @param mixed $fim Valro final
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereBetween($key, $ini, $fim, $type = 'AND')
Exemplo whereBetween
$eqps = Dao::table('apontamento_equipamento', 'ae')
->select('ae.SEQ_DB', 'ae.CLIENTE_SEQ_DB', 'ae.FUNCIONARIO_SEQ_DB', 'ae.HORIMETRO')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereBetween('ae.HORIMETRO', 100, 200)
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereDate
/**
* Adiciona condição de filtro por data específica
*
* @param string $key Coluna da condição
* @param string $date Valor Data inicial
* @param string $type Operador lógico das cláusulas (AND / OR)
*
* @return $this
*/
whereDate($key, $date, $type = 'AND')
Exemplo whereDate
$eqps = Dao::table('apontamento', 'ae')
->select('ae.SEQ_DB', 'ae.INI_DH', 'ae.FIM_DH')
->whereDate('ae.INI_DH', '16/01/2019')
->limit(100)
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereDateBetween
/**
* Adiciona condição por range de duas datas
*
* @param string $key
* @param string $ini Valor Data inicial
* @param string $fim
* @param string $type
*
* @return $this
*/
whereDateBetween($key, $ini, $fim, $type = 'AND')
Exemplo whereDateBetween
$eqps = Dao::table('apontamento', 'ae')
->select('ae.SEQ_DB', 'ae.INI_DH', 'ae.FIM_DH')
->whereDateBetween('ae.INI_DH', '20/01/2019', '31/01/2019')
->limit(100)
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereGroup e orWhereGroup
/**
* Adiciona condição where agrupada
*
* @param string $key
* @param string $ini Valor Data inicial
* @param string $fim
* @param string $type
*
* @return $this
*/
whereGroup(array $conditions)|| orWhereGroup(array $conditions)
Exemplo whereGroup
$eqps = Dao::table('apontamento_equipamento', 'ae')
->select(['ae.CLIENTE_SEQ_DB', 'ae.OS_SEQ_DB'])
->where([
'ae.CLIENTE_SEQ_DB' => 17503,
])
->whereGroup([
'OR' => [
['ae.OS_SEQ_DB', '=', 18067],
['ae.OS_SEQ_DB', '=', 18025],
],
])
->get();
echo '<pre>';
print_r($eqps);
echo '</pre>';
whereRaw
/**
* Adiciona filtro usando termos SQL.
*
* @param string $sql Cláusula condicional SQL
* @param mixed $values Valores da Cláusula
* @param string $boolean Operador lógico das cláusulas (AND / OR)
* 'AND' se não especificado
*/
public function whereRaw($sql, $values = [], $boolean = 'AND'): self
Exemplo whereRaw
$eqps = Dao::table('apontamento_equipamento', 'ae')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereRaw('SEQ_DB_DEVICE = 1548159687880')
->whereRaw('INI_DH between :ini and :fim', [
'ini' => '2021-10-01 08:00:00',
'fim' => '2021-10-01 23:59:59'
])
->get();
echo '`<pre>`';
print_r($eqps);
echo '`</pre>`';
// usando ::setParameters
$eqps = Dao::table('apontamento_equipamento', 'ae')
->where(['ae.CLIENTE_SEQ_DB' => 1396, 'ae.FUNCIONARIO_SEQ_DB' => 887])
->whereRaw('INI_DH between :ini and :fim')
->setParameters([
'ini' => '2021-10-01 08:00:00',
'fim' => '2021-10-01 23:59:59'
])
->get();
echo '`<pre>`';
print_r($eqps);
echo '`</pre>`';
orWhereRaw
/**
* Alias para adicionar filtro usando termos SQL e operador ‘OR’.
*
* @param string $sql Cláusula condicional SQL
* @param mixed $params Valores da Cláusula
*/
public function orWhereRaw($sql, $params = []): self
Exemplo orWhereRaw
$eqps = Dao::table('apontamento_equipamento', 'ae')
->where([
'ae.CLIENTE_SEQ_DB' => 1396,
'ae.FUNCIONARIO_SEQ_DB' => 887
])
->orWhereRaw('SEQ_DB_DEVICE = 1548159687880')
->get();
echo '`<pre>`';
print_r($eqps);
echo '`</pre>`';
Método de Ordenação, Limite e filtros rápidos
orderBy
/**
* Ordenação do resultado da consulta
* ::orderBy('coluna', 'ASC|DESC')
*
* @param string $field
* @param string $order
*
* @return $this
*/
orderBy($field, $order = ''): self
limit
/**
* Define número de registros retornados
*
* @param integer $limit
*
* @return $this
*/
limit($limit): self
enables()
/**
* Define que a consulta deve retornar apenas registros ativos
*
* @return $this
*/
enables(): self
disables()
/**
* Define que a consulta deve retornar apenas registros inativos
*
* @return $this
*/
disables(): self
all()
/**
* Define que a consulta deve retornar registros ativos e inativos
*
* @return $this
*/
all(): self
corporate()
/**
* Se deve aplicar filtros de filial/local na consulta ou não.
*/
public function corporate(?bool $corporate = true): self
groupBy
/**
* Agrupamento da query ou do array resultante (Legacy)
* ::groupBy('coluna')
* @calegarifabio @todo fazer/testar
* @param string $field
* @param string $order
*
* @return $this
*/
groupBy($field): self
getDS()
/**
* Retorna a estrtura de dados (DS - Data Structure) da tabela
* @calegarifabio
*
* @return object
*/
getDS(): object
getSql()
/**
* Retorna o sql/statemnt que foi gerado
*/
getSql()
echoSql()
/**
* Imprie o sql/statemnt que foi gerado e faz a consulta
*/
echoSql(): self
Metódos Legado
toArray()
/**
* Agrupamento dos registros pela CHAVE informada no GroupBy
* @tabelaBO
* @legacy
*
* @return $this
*/
toArray(): self
updateRow
/**
* Agrupamento dos registros pela CHAVE informada no GroupBy
* @tabelaBO
* @param array $values
*
* @return Retorno
*/
updateRow($aValues)
updateGpsPoint
/**
* Agrupamento dos registros pela CHAVE informada no GroupBy
* @tabelaBO
* @param float $latitude
* @param float $longitude
* @param string $posicaoDh
* @param string $fieldUpdate (INI ou FIM para tabelas Boletim)
*
* @return Retorno
*/
updateGpsPoint($latitude, $longitude, $posicaoDh = '', $fieldUpdate = 'POSICAO')
getSqlUpdateFklFields
/**
* Método que cria os SQL de update dos Campos FKL que usam essa tabela do primeiro parametro
* @param Tabela $tabela Recebe o objeto tabela (MOBILE_TABLE > 0)
* @param int $rowSeqDb É o SEQ_DB do registro que acabou de ser inserido ou do registro que estásendo alterado
* @param array $valores Array com os valores para insert/update que essa função usará para montaros updates
* @param boolean $insert para verificar se a tabela informada está com esse recurso desativado
*
* Tratado para compreender dois ou mais campos que apontam para a mesma entidade, por exemplo:
* TECNICO e AUXILIAR
* EQUIPAMENTO e IMPLEMENTO
*/
getSqlUpdateFklFields($tabela, $rowSeqDb, $valores, $insert = true)
getSeqDbFromSeqDbDevice
/**
* Metodo que pega o SEQ_DB de uma master ou mobile a partir do SEQ_DB_DEVICE
*
*/
getSeqDbFromSeqDbDevice($seqDbDevice): int
Outros
Tabela Upload:
getUploadContent
/**
* Retorna o campo conteudo da tabela NFS_UPLOAD em formato BASE64
* ->getUploadContent($fotoSeqDb, 'FOTO')
* ->getUploadContent($fotoSeqDb).
*/
public function getUploadContent(mixed $fieldSeqDb, string $fieldAlias = null): self
Acesso à tabela
$dados = Dao::table('upload')
->where(['SEQ_DB' => 1234])
->first();
Filtro Private User
private
/** executa a consulta ignorando o filtro de private user */
$disablePrivate = Dao::table('TABLE')->select(['SEQ_DB'])->private(false)->get();