How do I add a derived column to a model?
Example:
part table has these fields
id
description
model
partnumber
input
output
pdffile1
pdffile2
What we need is to be able to add
a field that mimics the regular sql case command
(case when input=5 then pdffile1 else pdfdile2 end) as whichpdf
how do we add "whichpdf" to the model with the case command..
it comes down to adding column to the model which does not exist in the data base.
Asked by rparkjr, on 4/12/09
1 Answer
Well, I would use a little Model callback magic to get what you're looking for.
In your part.php model I would create an afterFind($results) function that would check the input level and create a 'whichpdf' field as a key for your results mimicking a column in the database that doesn't actually exist and is dependent on input.
Here's an example:
function afterFind($results){
foreach($results as $key => $val){
if(isset($val[$this->alias]['input'])){
$input = $val[$this->alias]['input'];
if($input == 5){
$whichpdf = $val[$this->alias]['pdffile1'];
}
else{
$whichpdf = $val[$this->alias]['pdffile2'];
}
$results[$key][$this->alias]['whichpdf'] = $whichpdf;
}
}
return $results;
}
That will create a new key in your find results called 'whichpdf'. $this->Part->find('all') and give it a whirl.
You can read more about model callbacks in: http://book.cakephp.org/view/76/Callback-Methods
Hope that helps,
Nick
Answered by webtechnickon 5/12/09
THANKS!!! this worked wonderful..
reading the books and learning..
30 years of creating code in 9 coding languages and many operating system environments.. this is my first run through of Cakephp to help a customer over a hump..
Thanks again..
ron
rparkjr - on 6/12/09
Tagged with
Rating
1
Viewed
397 times
Last Activity
on 6/12/09