1

I have a legacy database linked to a CakePHP (2.5.3) application. 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. 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. Is there a way to force CakePHP to let me manually define the columns in the schema?

I have tried declaring the $_schema variable at the start of the model and that doesn't seem to help.

gotqn
  • 42,737
  • 46
  • 157
  • 243
Kez
  • 760
  • 5
  • 19

1 Answers1

2

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.

e.g.:

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);
}
Community
  • 1
  • 1
AD7six
  • 63,116
  • 12
  • 91
  • 123
  • This is great, thanks! It's working perfectly, though I had to make a couple changes to the code for it to work for me - there are too many closing brackets on the if statement and I had to replace $this->schema with $this->_schema. I have submitted an edit to your post. – Kez Jul 28 '15 at 13:20
  • 1
    I am not immune to typos =). – AD7six Jul 29 '15 at 05:33