martes, 15 de octubre de 2013

Realizar una consulta mutltitabla en CodeIgniter


Hoy vamos a ver cómo realizar una consulta mutltitabla en CodeIgniter
con la clase Active Record; esta clase es un patrón que nos permite
insertar, obtener, actualizar y eliminar los datos con un
mínimo de código. Para este ejemplo vamos a relacionar dos tablas,
las cuales tienen una relación de muchos a muchos; para hacer esta relación
vamos a necesitar una tabla conectora la cual va a tener los id de las dos
tablas a relacionar, esto significa que a la hora de hacer la consulta necesitamos
relacionar tres tablas.

Paso 1

descomprimos CodeIgniter en htdocs y llamamos al proyecto ciblog

paso 2

en la raíz de la aplicación creamos un archivo llamado .htaccess y le colocamos
este código:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /ciblog/index.php/$1 [L]
</IfModule>
<IfModule !mod_rewrite.c>
    ErrorDocument 404 /ciblog/index.php
</IfModule>

Paso 3

Vamos a ciblog/application/config/ y abrimos config.php y más o menos por la linea
17 definimos la base url

$config['base_url']    = 'http://localhost/ciblog/';

una lineas abajo, más o menos por la 29 quitamos el index.php

$config['index_page'] = '';

Paso 4

Definimos la conexión a la base de datos en ciblog/application/config/database.php
para mi caso los datos son los siguientes: lineas 51 - 54

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'ciblog';

Paso 5

Vamos a phpmyadmin y creamos la base de datos con el nombre de ciblog, dentramos
a esta y en la pestaña SQL ejecutamos el siguiente codigo:


CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `category` varchar(150) CHARACTER SET utf8 COLLATE utf8_spanish_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

--
-- Dumping data for table `categories`
--

INSERT INTO `categories` (`id`, `category`) VALUES
(1, 'Cms'),
(2, 'Php'),
(3, 'Framework');

-- --------------------------------------------------------

--
-- Table structure for table `comments`
--

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `comment` text COLLATE utf8_spanish_ci NOT NULL,
  `author` varchar(128) COLLATE utf8_spanish_ci NOT NULL,
  `entry_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci AUTO_INCREMENT=1 ;

-- --------------------------------------------------------

--
-- Table structure for table `entries`
--

CREATE TABLE IF NOT EXISTS `entries` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(128) COLLATE utf8_spanish_ci NOT NULL,
  `post` text COLLATE utf8_spanish_ci NOT NULL,
  `create_time` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_spanish_ci AUTO_INCREMENT=4 ;

--
-- Dumping data for table `entries`
--

INSERT INTO `entries` (`id`, `title`, `post`, `create_time`) VALUES
(2, 'CodeIgniter', 'CodeIgniter es un framework para desarrollo de aplicaciones - un conjunto de herramientas - para gente que\r\nconstruye sitios web usando PHP. Su objetivo es permitirle desarrollar proyectos mucho más rápido que lo que\r\npodría hacer si escribiera el código desde cero, proveyéndole un rico conjunto de bibliotecas para tareas comunes,\r\nasí como una interfaz sencilla y una estructura lógica para acceder a esas bibliotecas. CodeIgniter le permite\r\nenfocarse creativamente en su proyecto al minimizar la cantidad de código necesaria para una tarea dada.', '2013-10-11 00:00:00'),
(3, 'Wordpress', 'Wordpress es un CMS realizado con \r\nPHP, el cual tiene miles de plugins gratuitos y de pago; estos sirven para extender sus funcionalidades...', '2013-10-11 00:00:00');

-- --------------------------------------------------------

--
-- Table structure for table `entries_categories`
--

CREATE TABLE IF NOT EXISTS `entries_categories` (
  `entry_id` int(11) NOT NULL,
  `category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `entries_categories`
--

INSERT INTO `entries_categories` (`entry_id`, `category_id`) VALUES
(3, 2),
(2, 2),
(2, 3),
(3, 1);

Paso 6

Vamos a ciblog/application/models/ y creamos un archivo llamado blog_model.php

Código del Modelo blog_model.php

<?php

class Blog_Model extends CI_Model {
   
    function __construct() {
        parent::__Construct();
       
    }
   
 function get_all(){
       
    //$results = $this->db->query('SELECT * FROM entries ORDER BY create_time DESC');
   
    $this->db->order_by("title", "asc");
    $results = $this->db->get('entries');
   
    return $results->result();
   
 }   

 function get_categories($id){
   
          $this->db->select('*');
          $this->db->from('entries_categories');
          $this->db->where('entries_categories.entry_id ='.$id);
          $this->db->join('entries', 'entries.id = entries_categories.entry_id');
          $this->db->join('categories', 'categories.id = entries_categories.category_id');
          $this->db->order_by("category", "asc");         
  
    return $this->db->get()->result();                               
   
   }

}

Paso 7

Vamos a ciblog/application/controllers/ y creamos un contolador llamado blog.php

Código del controlador blog.php

<?php

/**
 *
 */
class Blog extends CI_Controller {
   
function __construct() {
        parent::__Construct();
        $this ->load->model('Blog_Model');
        $this->load->library('form_validation');
        $this->load->helper(array('date','url'));
   
}
   
function index(){
   
    $data['title']='Consulta multitabla';
    $data['results']=$this->Blog_Model->get_all();
   
    $this->load->view('posts',$data);   

   
}   

function post_category(){
         
          $id = $this->input->get('id', TRUE);
         
          $data['title']='Consulta multitabla';
          $data['results'] =  $this->Blog_Model->get_categories($id);   
      
          $this->load->view('post', $data);
   
}

}

Paso 8

Vamos a ciblog/application/views/ y creamos dos vistas; una con el nombre de
posts.php y la otra la llamamos post.php

Código de posts.php

<html>
<head>
<title><?php echo $title; ?></title>
</head>
<body>
<div align="center">
<?php  foreach($results as $result) {
   
       echo '<h3>'.$result->title.'</h3>';
       echo anchor('blog/post_category?id='.$result->id, 'Categoria(as)', 'title="'.$result->title.'"');
             

         }      
?>       
</div>
</body>
</html>

Codigo de post.php



<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><?php echo $title; ?></title>
</head>
<body>
<div align="center">
<?php

$num = 0;

if($results){

foreach ($results as $result) {
   
    if($num<1){
            echo '<strong>'.$result->title."</strong><br/><br>";
            echo $result->post."<br/><br>";
    }

    echo '<strong>'.$result->category."</strong><br/>";
   
    $num++;
   
}

}else{

echo "<h3>No tiene Categoria</h3>";

}
?>

</div>
</body>
</html>

Descargqar Ejemplo