How do I use this indirect relationship?

Posted by tyjkenn on Stack Overflow See other posts from Stack Overflow or by tyjkenn
Published on 2012-05-04T23:48:46Z Indexed on 2012/06/16 21:16 UTC
Read the original article Hit count: 275

Filed under:
|
|

I'm working on incorporating a reputation system into my site, similar to SO. Here is how it is structured:

User hasMany Project
User hasMany Answer
Project hasMany Rating
Answer hasMany Rating
Rating belongsTo Project where Rating.parent_type = Project
Rating belongsTo Answer where Rating.parent_type = Answer

Rating's value field will be a number between 1 and 5. The user should gain +10 for every 5-star review, +5 for every 4-star review, and +1 for every 3-star review. The way I currently have it set up is this: a recalcRep($id) action in the UsersController (along with other actions in other controllers, when necessary) calls the calcRep($id) method inside the User model, which is supposed to calculate the reputation of a user with an id of $id.

public function calcRep($id) {
        $rep = 0;

        $data = $this->Rating->find('all'); //does not work, because it is not directly associated
        foreach($data as $rating) {
            if(($rating['Rating']['parent_type'] == 'Project' && $rating['Project']['user_id']==$id) or ($rating['Rating']['parent_type'] == 'Answer' && $rating['Answer']['user_id']==$id)) {
                if($rating['Rating']['value']==5) {
                    $rep += 10;
                } else if($rating['Rating']['value']==4) {
                    $rep += 5;
                } else if($rating['Rating']['value']==3) {
                    $rep += 2;
                }
            }
        }
        $data['User']['reputation'] = $rep;
        $this->save($data);
    }

I may be approaching this in completely the wrong way, but I can't figure out how to find all the ratings that belong to any of the children of a specific user.

© Stack Overflow or respective owner

Related posts about orm

Related posts about relationship