简体   繁体   English

省略CakePHP模式中表中的大多数列

[英]Omit majority of columns from tables in CakePHP schema

I have a legacy database linked to a CakePHP (2.5.3) application. 我有一个链接到CakePHP(2.5.3)应用程序的旧数据库。 The database has a LOT of columns in all of its tables, many of which are completely unused (for example in one table I only need 2 columns out of 80 blank ones), so as a result I always have to specify 'fields' whenever I run a query. 数据库的所有表中都有很多列,其中许多列是完全未使用的(例如,在一个表中,我只需要80个空白列中的2列),因此,无论何时我总是必须指定“字段”我运行查询。 I read elsewhere that I can unset the fields by using code like this in the model: 我在其他地方读到我可以通过在模型中使用如下代码来取消设置字段:

function beforeFind($query) {
  $this->schema();

  unset($this->_schema['ColumnName']);
  unset($this->_schema['ColumnName2']);
  etc.
}

And this seems to work okay, the problem is that I am using 80+ lines of code to unset columns when really I only need to set two. 而且这似乎行得通,问题在于,当我实际上只需要设置两个时,我正在使用80多行代码来取消设置列。 Is there a way to force CakePHP to let me manually define the columns in the schema? 有没有一种方法可以强制CakePHP让我手动定义架构中的列?

I have tried declaring the $_schema variable at the start of the model and that doesn't seem to help. 我尝试在模型开始时声明$ _schema变量,但这似乎无济于事。

Override Model::schema 覆盖模型::模式

Model::schema is the method which tells CakePHP what fields exist, you need only override it to say explicitly what fields it should contain, or filter out the fields you don't want. Model :: schema是一种告诉CakePHP存在哪些字段的方法,您只需要重写它即可明确说明它应该包含哪些字段,或者过滤掉不需要的字段。

eg: 例如:

function schema($field = false) {
    if (!is_array($this->_schema) || $field === true) {
        parent::schema();
        $keepTheseKeys = array_flip(['Column1', 'Column2']);
        $this->_schema = array_intersect_key($this->_schema, $keepTheseKeys);
    }

    return parent::schema($field);
}

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

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