Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: Can I ignore a field when reading the Model from the DB?

Tags:

cakephp

In one of my models, I have a "LONGTEXT" field that has a big dump of a bunch of stuff that I never care to read, and it slows things down, since I'm moving much more data between the DB and the web app.

Is there a way to specify in the model that I want CakePHP to simply ignore that field, and never read it or do anything with it?

I really want to avoid the hassle of creating a separate table and a separate model, only for this field.

Thanks!
Daniel

like image 627
Daniel Magliola Avatar asked Dec 13 '22 21:12

Daniel Magliola


2 Answers

As @SpawnCxy said, you'll need to use the 'fields' => array(...) option in a find to limit the data you want to retrieve. If you don't want to do this every time you write a find, you can add something like this to your models beforeFind() callback, which will automatically populate the fields options with all fields except the longtext field:

function beforeFind($query) {
    if (!isset($query['fields'])) {
        foreach ($this->_schema as $field => $foo) {
            if ($field == 'longtextfield') {
                continue;
            }
            $query['fields'][] = $this->alias . '.' . $field;
        }
    }
    return $query;
}

Regarding comment:

That's true… The easiest way in this case is probably to unset the field from the schema.

unset($this->Model->_schema['longtextfield']);

I haven't tested it, but this should prevent the field from being included in the query. If you want to make this switchable for each query, you could move it to another variable like $Model->_schemaInactiveFields and move it back when needed. You could even make a Behavior for this.

like image 89
deceze Avatar answered Jun 03 '23 01:06

deceze


The parameter fields may help you.It doesn't ignore fields but specifies fields you want:

array(
'conditions' => array('Model.field' => $thisValue), //array of conditions
'fields' => array('Model.field1', 'Model.field2'), //list columns you want
)

You can get more information of retrieving data in the cookbook .

Another idea:

Define your special query in the model:

function myfind($type,$params)
{
     $params['fields'] = array('Model.field1','Model.field2',...);
     return $this->find($type,$params);
}

Then use it in the controller

$this->Model->myfind($type,$params);
like image 35
Young Avatar answered Jun 03 '23 01:06

Young