简体   繁体   English

将cakephp模型关联到非c​​akephp数据库表

[英]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? 是否可以在CakePHP应用程序中创建模型并将该模型与根本不与CakePHP应用程序关联的数据库表相关联?

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). 例如,该数据库表属于另一个应用程序,我们想在CakePHP中创建一个使用该表的模型(因此该表完全不符合CakePHP的约定)。 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) 我需要在模型中放入什么才能使关联在不更改表的情况下正常工作(我需要能够对该表执行基本的CRUD操作)

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 : 例如,如果您有一个带有idCandidat主键的cand表,则可以创建一个模型并使用$ useTable和$ primaryKey属性:

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): 为此,您可以使用(我将只扩展@chroonoss的示例,因为它是正确的):

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. 这将允许您使用其他DataSource连接。 These are defined in: app/config/database.php . 这些定义在: app/config/database.php You have to have a property named "external" there for this example to work: 您必须具有一个名为“ external”的属性,此示例才能正常工作:

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. 当然,您可以根据需要命名DataSource。

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: 您可以在查找功能中设置字段(列) -http://book.cakephp.org/1.3/en/view/1018/find或者,如果您希望将字段设置为关联,则可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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