简体   繁体   中英

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

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.

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.

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')
   )
); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM