Advertisement
christiansalazarh

Ejemplo completo de uso de JOIN (CDbCriteria)

Jan 11th, 2013
377
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.08 KB | None | 0 0
  1. class Perrito extends CActiveRecord {
  2.   // $id, $name  
  3. }
  4.  
  5. class PerritoCorrea extends CActiveRecord {
  6.   // $perrito_id, $correa_id  
  7. }
  8.  
  9. class Correa extends CActiveRecord {
  10. // $id, $color
  11.  
  12.     public function listarPorPerrito($nombre_perrito){
  13.         $c = new CDbCriteria();
  14.  
  15.         // queremos buscar las correas del "Perrito.name" igual a "KIM",
  16.         // pero pasando por toda la relacion:
  17.         //
  18.         // select * from Correa 't'  <-- CDbCriteria pone la 't' automaticamente
  19.         //  left join PerritoCorrea PXC on PXC.correa_id = t.id
  20.         //  left join Perrito PX on PX.id = PXC.perrito_id
  21.         // where
  22.         //   PX.name like '%KIM%'
  23.        
  24.         $px  = Perrito::model()->tablename();
  25.         $pxc = PerritoCorrea::model()->tablename();
  26.         $c->join =
  27.            'left join '.$pxc.' PXC on PXC.correa_id = t.id'
  28.           .'left join '.$px.' PX on PXC.perrito_id = PX.id'
  29.         ;
  30.         $c->compare('px.name',$nombre_perrito,true); // <-- 'true' indica "Like"
  31.  
  32.         return new CActiveDataProvider($this,array(
  33.            'criteria'=>$c,
  34.            'pagination'=>array('pageSize'=>5),
  35.             // el sort no lo pongo para no sacar de foco el ejemplo, pero considera
  36.             // que tu criteria $c dispone de PX.id, PX.name (PX es Perrito), por
  37.             // tanto puedes usar esos nombres para ordernar. experimentar con eso.
  38.         ));
  39.     }
  40. }
  41.  
  42. [COMO USAR]
  43.  
  44. // protected/views/xxx/correas.php
  45. $this->widget('zii.widgets.grid.CGridView', array(
  46.    'dataProvider'=>$dataProvider,
  47. ));
  48.  
  49. // protected/controller/xxxController.php
  50. public function actionListarCorreas($perrito){
  51.   $dp = Correa::model()->listarPorPerrito($perrito);
  52.   $this->render('correas',array('dataProvider'=>$dp));
  53. }
  54.  
  55. // ejemplo:
  56. index.php?r=/xxx/listarcorreas&perrito=kim
  57.  
  58. // con ajax:
  59. $.ajax({
  60.   url: 'index.php?r=/xxx/listarcorreas&perrito=kim',
  61.   cache: false, type: 'get',
  62.   success: function(html){
  63.     // $.fancybox(html);  <- si usas fancybox
  64.     // o a rin pelao usando un <div id='ventanita'></div>
  65.     $('#ventanita').html(html);
  66.   }
  67. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement