Axiol
Axiol

Reputation: 5962

Find multiple elements of a sub-array entry

So, I'ld like to add a "Like" system on something I'm working on and I have a bit of trouble with it.

So my DB's table for my likes is like this :

========================================
|| *id* | created | user_id | post_id ||
========================================

I'm with with counting the number of likes for a post and all. The problem I have is I want to find if the logged user has already liked the post is is viewing so the "Like" link would become an "Unlike" link. And that's my problem. I can't manage to imagine how to do it.

Any help ?

Upvotes: 0

Views: 95

Answers (1)

tigrang
tigrang

Reputation: 6767

Look at Model::hasAny() method:

$userHasLikedThisPost = $this->Like->hasAny(array(
    'user_id' => $this->Auth->user('id'), 
    'post_id' => $postId
));

Then simply set a view var and output the corresponding link.

Make a helper method in the model so its more re-usable:

public function hasLike($postId, $userId) {
    return $this->hasAny(array(
        'user_id' => $userId, 
        'post_id' => $postId,
    ));
}

Upvotes: 1

Related Questions