How to use databases in Cakephp without complying with naming conventions?

Asked

Viewed 1,038 times

9

Cakephp has conventions for naming tables, classes, etc., such as having columns username and password for tables that save users. In my current situation, I have tables that do not obey these standards.

How you could continue using the framework’s facilities and resources, without modifying the names of all tables, and columns?

2 answers

8


You can force the table name in the model definition:

class MeuModel extends AppModel {
    public $useTable = 'minha_tabela';
}

Columns can have the name you want, and it is recommended that the table has a PK with autoincrement called id. If your PK has another name, you can force one, but it needs to be a simple PK (i.e., not composed of multiple columns):

class MeuModel extends AppModel {
    public $useTable = 'minha_tabela';
    public $primaryKey = 'minha_tabela_id';
}

In relation to columns username and password, names can be configured when you include the component Auth in Controller. For example, to use a field called email instead of username:

public $components = array(
    'Auth' => array(
        'authenticate' => array(
            'Form' => array(
                'fields' => array('username' => 'email')
            )
        )
    )
);

More details on section of the manual on authentication.

  • In my case, the PK corresponds to the name of the table + _id, example "usuarios_id", "eventos_id". It has how to circumvent?

  • 2

    Yes @Calebeoliveira, see my updated reply with an example.

1

Complementing the @bfavaretto response, don’t forget to call the model in the controller.

QualquerController extends appController {
    // $uses atribui o model 'MEU'.
    public $uses = 'Meu';
}

This solves the problem of the driver requiring you to call your controller 'My', to use a 'My' model'.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.