baur79
baur79

Reputation: 273

Using existing field name as different name

i have existing website.
and i write the new back-end (in cakephp) without changing front-end programm

the discomfort that db table has field names as
id
news_date
news_title
news_content

is it possiable to do something in cakephp model file (reindentify the field names) so i can use model in controller as
News.date
News.title
News.content

Upvotes: 2

Views: 1649

Answers (2)

Tim
Tim

Reputation: 5933

Is said by Dunhamzz, virtualFields are a good solution until you want to work with these new field-names.

Since I assume your frontend needs to use the old names from the database I would go with the afterFind-callback in your model.
Let's say you've got the model news.php:

# /app/model/news.php

function afterFind($results) {
    foreach ($results as $key => $val) {
        if (isset($val['News']['title'])) {
            $results[$key]['News']['news_title'] = $val['News']['title']);
            # unset($results[$key]['News']['title']); //use this if you don't want the "new" fields in your array
        }
        if (isset($val['News']['date'])) {
            $results[$key]['News']['news_date'] = $val['News']['date']);
            # unset($results[$key]['News']['date']); //use this if you don't want the "new" fields in your array
        }
        if (isset($val['News']['content'])) {
            $results[$key]['News']['news_content'] = $val['News']['content']);
            # unset($results[$key]['News']['content']); //use this if you don't want the "new" fields in your array
        }
    }
    return $results;
}

You need to rename the database-fields to your new wanted value. You then can use these within conditions like every other field.
Only difference is, that you get back an array where all your fields have been renamed to your frontend-fields.

For more information about the available callback-methods have a look here: Callback Methods

Upvotes: 1

Dunhamzzz
Dunhamzzz

Reputation: 14798

What you need to do is setup some very basic virtual fields in your news model. Something like this should suit your needs.

public $virtualFields = array(
    'title' => 'news_title',
    'date' => 'news_date',
    'content' => 'news_content'
);

Also do yourself a favour by checking out the other model attributes that could help you out, you'll want to set displayType as new_title I'd imagine.

Upvotes: 2

Related Questions