Relate the 2 tables


#1

Hi, I do not know how to do the following:

I have 2 tables:

  • Users
  • Profile

Users:

  • id
    -profile_id
  • First name
  • Surname
  • Mail
  • Password

Profile:

  • id
  • Photo
  • First name
  • Surname

I want to relate the 2 tables, recover the data of the 2 tables when I consult the id of the user.

With other tables I would have no problem with a join, but I have no idea how to do it with UsersController:

 public function login() {
   $isPost = $this->request->is('POST');
        if($isPost) {
         $user = $this->Auth->identify();
         if($user) {
           $this->Auth->setUser($user);
           $this->set('user', $user);
           return $this->redirect($this->Auth->redirectUrl());
         }
         else {
           $this->Flash->error(__('Email o contraseña incorrecta.', ['key' => 'auth']));
         }
       }
       if($this->Auth->user()) {
         $this->Auth->logout();
         $this->redirect($this->referer());
       }
  }

#2

you can use https://book.cakephp.org/3.0/en/controllers/components/authentication.html#customizing-find-query
and put any ->contain in there


#3

"contain option have been deprecated as of 3.1"


#4

you are mistaking contain option of Auth component with ->contain function of query builder:

public function findAuth(\Cake\ORM\Query $query, array $options)
{
    $query
        ->contain(['Profiles']);

    return $query;
}

#5

Yes, in the end I built the query with join:

public function findAuth(\Cake\ORM\Query $usuario, array $options){
$usuario->join(['Perfil'=> [
                                    'table' => 'perfil',
                                    'type' => 'LEFT',
                                    'conditions' => 'Perfil.id = perfil_id'
                                   ]
                     ])
              ->join(['Imagenes'=> [
                                    'table' => 'imagenes',
                                    'type' => 'LEFT',
                                    'conditions' => 'Imagenes.id = Users.imagen_id'
                                   ]
                     ])
            ->select([
                      'Users.id', 'Users.persona_id', 'Users.nombre', 'Users.apellido',  'Users.email', 'Users.password', 'Users.role', 'Users.active', 'Users.creado', 'Users.modificado',
                      'usuarioNombre' => 'Perfil.nombre',
                      'usuarioPrimerApellido' => 'Perfil.primer_apellido',
                      'usuarioSegundoApellido' => 'Perfil.segundo_apellido',
                      'imagen' => 'Imagenes.imagen'
                     ])
            ->first();
      return $usuario;
 }
}

#6

hello, do not complicate yourself use the cakephp console creating the model and the user and profile controller and it will create the relationships in the model. otherwise you create the relationships manually in your belongsto and hasmany model.