Question

Ok, I have a problem with my Yii models. I have a 1: m relationship between the tables "besuch" and "note".

Note:

id_note    note    wertung    besuch_id 
   1        4        0.5         1
   2        5         1          1
   3        4.5       2          1

besuch:

id_besuch   user_id   fach_id    ...
    1          1         1

Now I want to create a gridview of the "besuch". In this gridview one column should be "average". This average is calculated like this:

average = all(note.note * note.wertung) / Sum(note.wertung) 

where id_besuch = besuch_id

Example:

average = (4 * 0.5 + 5 * 1 + 4.5 * 2) / 0.5 + 1 + 2 = 
16 / 3.5 = 
4.571...

Now I would like to implement this function into my gridView like this:

array(
    'name' => 'average',
    'value' => '$data->average'
),

I know that this is just an abstract representation of what i want.

Has someone a good idea or can someone say where i need to implement a funciton like this?

thanks

Was it helpful?

Solution

Ok if i understood your problem then you can do like this.

  1. First make a function in your model besuch like
public function calculateAverage($id)
{
    $numerator=0;
    $denominator=0;
    $notes=Note::model()->findAllByAttributes(array('besuch_id'=>$id));
    foreach($notes as $note)
    {
        $numerator=$numerator+($note->note*$note->wertung);
        $denominator=$denominator+$note->note;
    }
    $result=$numerator/$denominator;
    return $result;
}

Now in your grid you can us it as

array(
    'header' => 'Average',
    'value' => '$data->calculateAverage($data->id)'
),
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top