【问题标题】:multiple database relationship on field other than primary key in CakePHPCakePHP中除主键以外的字段上的多个数据库关系
【发布时间】:2010-12-18 12:39:40
【问题描述】:

我有一个项目必须跨越多个数据库。

一个数据库有表:

CREATE TABLE device {
  device_uid integer unsigned not null primary key auto_increment,
  os varchar(50),
  name varchar(50)
}

CREATE TABLE platform {
  platform_id integer unsigned not null primary key auto_increment,
  name varchar(50)
}

另一个数据库有表:

CREATE TABLE oses_platforms {
  platform_id integer unsigned not null primary key auto_increment,
  os varchar(50),
  platform_id integer unsigned
}

我已经为表格和关系创建了模型:

<?php
class Platform extends AppModel {

    var $name = 'Platform';
    var $useTable = 'platform';
    var $primaryKey = 'platform_id';
    var $useDbConfig = 'otherdb';

    var $hasOne = array(
        'OsesPlatform' => array(
            'className' => 'OsesPlatform',
            'foreignKey' => 'platform_id'
        )
    );
}

class Device extends AppModel {

    var $name = 'Device';
    var $primaryKey = 'device_uid';
    var $useDbConfig = 'otherdb';        

}

class OsesPlatform extends AppModel {

    var $useDbConfig = 'default';
    var $name = 'OsesPlatform';
    var $primaryKey = 'os';


        var $belongsTo = array(
                'Platform' => array(
                        'className' => 'Platform',
                        'foreignKey' => 'platform_id',                            
                ),
        );

        var $hasMany = array(
                'Device' => array(
                        'className' => 'Device',
                        'foreignKey' => 'os',
                        'dependent' => false,                            
                )
        );
}
?>

如果所有三个表都驻留在“default”或“otherdb”中,我可以在从 Device 到 OsesPlatform 的 hasOne 或 belongsTo 关系的“conditions”参数中执行此操作,实际上 Platform 和 OsesPlatform 之间的 hasOne 关系工作正常.但是,我需要建模的是设备和平台之间的关系。

【问题讨论】:

    标签: php cakephp associations multiple-databases


    【解决方案1】:

    也许这个页面解释了你所追求的代码: http://blog.4webby.com/posts/view/6/cakephp_models_using_multiple_db_connections

    希望对您有所帮助。

    西蒙。

    【讨论】:

    • 谢谢,但它没有回答我的问题:如何在模型中加入?我认为在这种情况下,我将不得不捏住鼻子并在 Controller 中执行此操作。
    【解决方案2】:

    我尝试在 cakeapp.com 中重新创建您的结构。 看看http://cakeapp.com/sqldesigners/sql/oses的架构

    但是当我尝试在此处自动创建的应用程序中添加设备时:http://oses.cakeapp.com/cake/oses/devices/add 似乎有点错误。

    您可以使用密码“oses”更改数据库结构。并让 cakeapp.com 通过单击链接 #3 自动创建应用程序:“Build the CakeApp application based on the settings and the SQL”

    也许这对你有帮助?

    【讨论】:

    • 嗯,你在“设备”中添加了另一个字段,我做不到。我意识到我没有提到这一点。无论如何,加入需要在 devices.os 上,而不是在 devices.osesplatform_id 上。
    【解决方案3】:

    事实证明,Cake 并未正式支持跨数据库的 HABTM 关系(来自 #cakephp 上的 markstory)。虽然它有时会起作用,但尚不清楚(至少对我而言)它在什么条件下起作用,并且没有计划改进对此的支持。所以我必须用另一种方式来做这件事。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      相关资源
      最近更新 更多