Skip to content

Instantly share code, notes, and snippets.

@rmgimenez
Last active June 7, 2016 12:35
Show Gist options
  • Save rmgimenez/4a3a9a6ee5e2790bcc294304ad49dbb5 to your computer and use it in GitHub Desktop.
Save rmgimenez/4a3a9a6ee5e2790bcc294304ad49dbb5 to your computer and use it in GitHub Desktop.
Classe que extende a classe padrão de model do CodeIginiter. Com essa classe fica mais fácil fazer consultas no banco de dados usando o CodeIginiter. É importante que a chave das suas tabelas seja o campo com o nome "id"
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// http://jeromejaglale.com/doc/php/codeigniter_models
// Salvar em : application/core/MY_Model.php
class MY_Model extends CI_Model {
var $table = "";
function __construct()
{
parent::__construct();
$this->load->database();
}
function insert($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
function find_id($id)
{
if ($id == NULL)
{
return NULL;
}
$this->db->where('id', $id);
$query = $this->db->get($this->table);
$result = $query->result_array();
return (count($result) > 0 ? $result[0] : NULL);
}
function find_all($sort = 'id', $order = 'asc')
{
$this->db->order_by($sort, $order);
$query = $this->db->get($this->table);
return $query->result_array();
}
function update($id, $data)
{
$this->db->where('id', $id);
$this->db->update($this->table, $data);
}
function delete($id)
{
if ($id != NULL)
{
$this->db->where('id', $id);
$this->db->delete($this->table);
}
}
}
/* End of file */
// Aqui começa outro arquivo:
// exemplo de um model que extende da classe MY_Model acima
// arquivo salvo em: application/models/book.php
<?php
class Book extends MY_Model {
function __construct()
{
parent::__construct();
$this->table = 'book'; // nome da tabela, igual a que está no banco de dados
}
}
/* End of file */
//Abaixo segue exemplos de como usar no controller a classe criada
// Inserir
$this->load->model('book');
$book = array();
$book['title'] = 'The Black Dahlia';
$book['author'] = 'James Ellroy';
$this->book->insert($book);
Encontrar por ID
$this->load->model('book');
$book = $this->book->find_id('47');
echo $book['title'];
Excluir registro
$this->load->model('book');
$this->book->delete('47');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment