4.9 KiB
4.9 KiB
name, description, layer
| name | description | layer |
|---|---|---|
| perfex-database | Operações de base de dados em módulos Perfex CRM — db_prefix(), options, queries e Active Record. Baseado apenas na documentação oficial. | wiki |
/perfex-database - Base de Dados Perfex CRM
Operações de base de dados em módulos. Zero assumptions, zero hallucinations - apenas documentação oficial.
Documentação Base
Regra Fundamental: db_prefix()
SEMPRE usar db_prefix() em todas as queries.
O Perfex CRM suporta prefixos de tabela customizados. O default é tbl, mas pode ser alterado.
// CORRECTO
$CI->db->get(db_prefix() . 'meu_modulo');
// ERRADO - quebra se prefix não for "tbl"
$CI->db->get('tblmeu_modulo');
Aceder à Base de Dados
Em Controllers/Models
// Acesso directo
$this->db->get(db_prefix() . 'clients');
Fora de Controllers/Models
$CI = &get_instance();
$CI->db->get(db_prefix() . 'clients');
Criar Tabelas (Activation Hook)
function meu_modulo_activation_hook()
{
$CI = &get_instance();
// Verificar se tabela existe
if (!$CI->db->table_exists(db_prefix() . 'meu_modulo')) {
$CI->db->query('
CREATE TABLE `' . db_prefix() . 'meu_modulo` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`client_id` INT(11) UNSIGNED NOT NULL,
`name` VARCHAR(255) NOT NULL,
`description` TEXT,
`amount` DECIMAL(15,2) NOT NULL DEFAULT 0.00,
`status` VARCHAR(50) NOT NULL DEFAULT "pending",
`created_at` DATETIME NOT NULL,
`updated_at` DATETIME DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `client_id` (`client_id`),
KEY `status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=' . $CI->db->char_set . ';
');
}
}
Query Builder (Active Record)
SELECT
// Todos os registos
$result = $this->db->get(db_prefix() . 'meu_modulo')->result();
// Com condições
$this->db->where('status', 'active');
$this->db->where('client_id', $client_id);
$result = $this->db->get(db_prefix() . 'meu_modulo')->result();
// Seleccionar campos específicos
$this->db->select('id, name, amount');
$this->db->where('status', 'active');
$result = $this->db->get(db_prefix() . 'meu_modulo')->result();
// Um registo
$this->db->where('id', $id);
$row = $this->db->get(db_prefix() . 'meu_modulo')->row();
// Com LIKE
$this->db->like('name', $search);
$result = $this->db->get(db_prefix() . 'meu_modulo')->result();
// Com ORDER BY
$this->db->order_by('created_at', 'DESC');
$result = $this->db->get(db_prefix() . 'meu_modulo')->result();
// Com LIMIT
$this->db->limit(10, 0); // 10 registos, offset 0
$result = $this->db->get(db_prefix() . 'meu_modulo')->result();
// JOIN
$this->db->select('m.*, c.company as client_name');
$this->db->from(db_prefix() . 'meu_modulo as m');
$this->db->join(db_prefix() . 'clients as c', 'c.userid = m.client_id', 'left');
$result = $this->db->get()->result();
INSERT
$data = [
'client_id' => $client_id,
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
'amount' => $this->input->post('amount'),
'status' => 'pending',
'created_at' => date('Y-m-d H:i:s'),
];
$this->db->insert(db_prefix() . 'meu_modulo', $data);
$insert_id = $this->db->insert_id();
UPDATE
$data = [
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
'amount' => $this->input->post('amount'),
'updated_at' => date('Y-m-d H:i:s'),
];
$this->db->where('id', $id);
$this->db->update(db_prefix() . 'meu_modulo', $data);
// Verificar se actualizou
$affected = $this->db->affected_rows();
DELETE
$this->db->where('id', $id);
$this->db->delete(db_prefix() . 'meu_modulo');
COUNT
// Contar todos
$count = $this->db->count_all(db_prefix() . 'meu_modulo');
// Contar com condições
$this->db->where('status', 'active');
$count = $this->db->count_all_results(db_prefix() . 'meu_modulo');
Sistema de Opções
Para guardar configurações simples (key-value).
add_option()
Cria opção nova. NÃO sobrescreve se existir.
add_option('meu_modulo_enabled', '1');
add_option('meu_modulo_config', serialize(['key' => 'value']));
// Com autoload (0 = não, 1 = sim)
add_option('meu_modulo_setting', 'valor', 0);
get_option()
Obtém valor da opção.
$enabled = get_option('meu_modulo_enabled');
$config = unserialize(get_option('meu_modulo_config'));
// Retorna string vazia se não existir
if (get_option('meu_modulo_setting') === '') {
// Opção não existe
}
update_option()
Actualiza ou cria opção (v2.3.3+).
update