0

I have a problem when using CakePHP HABTM.

I have the following models.

class Repositorio extends AppModel{
    var $name="Repositorio";

    var $hasAndBelongsToMany = array(
        'Sesion' =>
            array(
                'joinTable' => 'sesions_repositorios',
                'dependent' => true 
            )
        );

    var $order=array('Repositorio.name'=>'ASC');
}

class Sesion extends AppModel{
    var $name="Sesion";

    var $belongsTo=array(
        'SesionsEstado',
        'Asignatura',
        'User'
    );

    var $hasAndBelongsToMany = array('Repositorio'=>
        array(
            'joinTable'=>'sesions_repositorios',
            'dependent' => true 
        )
    );

    var $order=array('Sesion.ffin'=>'ASC');
}

And the following database tables.

CREATE TABLE sesions (
  id INT(11) NOT NULL AUTO_INCREMENT,
  user_id INT(11) NOT NULL,
  sesions_estado_id INT(11) NOT NULL,
  asignatura_id INT(11) NOT NULL,
  name VARCHAR(100) NOT NULL,
  finicio DATETIME NOT NULL,
  ffin DATETIME NOT NULL,
  created DATETIME NOT NULL,
  modified DATETIME NOT NULL,
  PRIMARY KEY(id),
  INDEX sesions_FKIndex1(sesions_estado_id),
  INDEX sesions_FKIndex2(asignatura_id),
  INDEX sesions_FKIndex3(user_id)
);

CREATE TABLE repositorios (
  id INT(11) NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  created DATETIME NOT NULL,
  modified DATETIME NOT NULL,
  PRIMARY KEY(id)
);

CREATE TABLE sesions_repositorios (
  id INT(11) NOT NULL AUTO_INCREMENT,
  sesion_id INT(11) NOT NULL,
  repositorio_id INT(11) NOT NULL,
  PRIMARY KEY(id),
  INDEX sesions_repositorios_FKIndex1(sesion_id),
  INDEX sesions_repositorios_FKIndex2(repositorio_id)
);

When I save the data in a repository all work properly, that is, it performs an INSERT on the table "repositorios" and performs the corresponding INSERT on table "sesions_repositorios.

My problem comes when I get a list of repositories for a particular user. The code for this would be.

class RepositoriosController extends AppController{
...
$r=$this->Repositorio->Sesion->find('all', array('conditions'=>array('user_id'=>$this->Session->read('Auth.User.id'))));
var_dump($r);
...
}

The $r variable does not contain the filtered data for user_id, why?, what am I doing wrong?

I have not set foreign key's, could that be the problem?

Thanks for the help.

Lobo
  • 4,001
  • 8
  • 37
  • 67

2 Answers2

0

I believe that you need to add in something like 'recursive' => 1 or whatever depth you want it to search your linked models into your query.

$r=$this->Repositorio->Sesion->find('all', array('conditions'=>array('user_id'=>$this->Session->read('Auth.User.id')),'recursive'=>1));
0

I'm sorry, the code is actually quite correct. Was failing by other issues.

Thanks for everything.

Greetings!

Lobo
  • 4,001
  • 8
  • 37
  • 67