Skip navigation.

极湖

无不用其“极”

CakePHP 动态设置 tablePrefix 的一个例子

, ,

遇到一个问题

用 CakePHP 开发的网站,有几个子网站,每个子网站有一个 webroot,共用数据库,其中有部分数据表格不能共用,因此需要根据实际情况设置表格的前缀。

这个在 CakePHP 下其实很简单,只是没有先例,所以摸索了半天,最后得出的方法如下:

首先,在各个 webroot 下的 index.php 追加一个常量(在载入 bootstrap.php 之前)

例:
app/webroot-a/index.php
define('SITE_ID', 1);

app/webroot-b/index.php
define('SITE_ID', 2);

app/webroot-c/index.php
define('SITE_ID', 3);


然后,在需要不同前缀的表格的 Model 中加入 settableprefix() 函数

例:
app/models/users.php
<?php
class Users extends AppModel {
    var $name = 'Users';
    var $useTable = 'users';
    var $primaryKey = 'user_id';

    function settableprefix() {
        if(SITE_ID == 1) {
            $this->tablePrefix = 'a_';
        } elseif(SITE_ID == 2)  {
            $this->tablePrefix = 'b_';
        } elseif(SITE_ID == 3)  {
            $this->tablePrefix = 'c_';
        }
    }
}
?>

这样就可以了。

其实,index.php 中的常量也可以不用追加,直接利用现成的常量就行,比如 WEBROOT_DIR。追加常量是为了程序照顾运行的效率。

cakePHP 动态选择数据库连接的方法获取 PostgreSQL 数据库之 sequence 名称列表的 SQL

Write a comment

You must be logged in to write a comment. If you're not a registered member, please sign up.

January 2010
S M T W T F S
December 2009February 2010
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30