views:

39

answers:

2

Is it somehow possible to create a hasMany Relationship which makes use of an ID outside of the Model? For example one User has many Comments, but I would like to find just the comments of the logged in user:

public $hasMany = array(
    'MyComment' => array(
            'className' => 'Comment',
            'foreignKey' => 'user_id',
            'dependent' => false,
            'conditions' => array('Comment.user_id' => $loggedinUser_id),
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
);

I was thinking of passing the $loggedinUser_id in the controllers beforeFilter() to the model. Is this a good way to solve this issue or are there better ways?

Any suggestion is appreciated. Thanks a lot!

A: 

Are you always and only going to want to access the logged in user's comments? Aren't you going to want to show other people's comments at some point in time?

I'd suggest you just set that as a condition in each call to Model::find() from your controller.

Also, depending on specific types of relationships, you may need to use the Containable behavior to filter based on related model criteria (generally for HABTM rather than HM).

Travis Leleu
Thanks for you answer and sorry for my bad explanation. Please see my comment on @cdburgess answer.
chris
+2  A: 

I would advise following the "fat model, skinney controller" way of thinking. I would build a function in the model called: user_only_comments (or something that would make sense to you).

// in the comment model
function user_only_comments($id) {
   return $this->find('all', array('conditions' => array('Comment.user_id' => $id)));
}

Then in the controller, you just call:

$user_comments = $this->Comment->user_only_comments($user_id);

Then you are good to go and your controller is not only nice and clean, but you can call this model specific method anywhere without having to write the conditions every time. If the conditions change, you can change it on one place in stead of everywhere in the controller you set the condition.

cdburgess
Ok, my explanation was very bad, sorry for that.I want to get all comments and every comment has many "likes" from different users. Now I need to know whether or not the logged in user has liked a comment.Thats why I would like to create a special Relationship in the Model which just tells me if the logged in user has liked the comment.
chris