user765368
user765368

Reputation: 20346

associate cakephp model to non-cakephp database table

is it possible to create a model in a CakePHP application and associate that model with a database table that is not associated with a cakePHP application at all?

For example, that database table belongs to another application and we want to create a model in CakePHP that uses that table (so that table is not conforming to CakePHP's convention at all). How do I do this? What do I need to put in my Model in order for that association to work WITHOUT changing my table (I need to be able to perform the basic CRUD operations on that table)

Any idea please?

thank you

Upvotes: 0

Views: 855

Answers (3)

Mindaugas Norvilas
Mindaugas Norvilas

Reputation: 532

You can set fields (columns) in find function - http://book.cakephp.org/1.3/en/view/1018/find Or if you want to set fields to association, you can do this:

var $belongsTo = array(
  'User' => array(
    'className' => 'User',
    'foreignKey' => 'user_id',
    'fields' => array('name','phone')
   )
); 

Upvotes: 0

Borislav Sabev
Borislav Sabev

Reputation: 4856

You can even use a table that is in a totally different Database or on a different server. For this you can use (I will just extend @chroonoss 's example as it is correct):

class Candidat extends AppModel{
var $name = 'Candidats';
var $useTable = 'cand';
var $primaryKey  = 'idCandidat';

var $usedbConfig = 'external';
}

This will allow you to use a different DataSource connetion. These are defined in: app/config/database.php. You have to have a property named "external" there for this example to work:

public $external = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => '101.180.10.17',
        'login' => 'username',
        'password' => 'yourTopSecretPassword',
        'database' => 'database_name',
        'prefix' => '',
        'encoding' => 'utf8',
    );

Of course you can name your DataSource as you like.

Upvotes: 0

mohamed mellouki
mohamed mellouki

Reputation: 613

Yes you can do that. For example if you have a cand table with idCandidat primary key,you create a model and use the $useTable & $primaryKey properties :

class Candidat extends AppModel{
var $name = 'Candidats';
var $useTable = 'cand';
var $primaryKey  = 'idCandidat';
//etc.
}

and you continue using your model in controller like you'll be doing with a normal one.

Upvotes: 1

Related Questions