I have Users and Courses. They have a HABTM relationship that is manifested as Subscriptions (that's the table with user_id and course_id).
I need to have a condition on the Course page that checks if the user is subscribed to this course. I am not sure how to do that.
I have this $subscriptions set in the AppController in order to give me a menu of only subscribed courses in the nav:
$this->set('subscriptions', ClassRegistry::init('Subscription')->find('all',
array(
'fields' => array('Course.id', 'Course.name'),
'conditions' => array('Subscription.user_id =' => $this->Auth->user('id')),
'recursive' => 1
)));
My question: How do I check to see if the subscription exists already? I basically need to find if there's a subscription with user_id that's the same as logged in user, and a course_id the same as the current course I'm in.
Thanks!
How about something like this?:
$exists = (bool) $this->Subscription->field('count', array(
'conditions' => array(
'user_id' => $this->Auth->user('id'),
'course_id' => $courseId
)
));
Side note: don't use recursive
. Set it to public $recursive = -1;
in your AppModel, and then never set it again. If you want to include "extra" data, use Cake's Containable Behavior - it's consistent, and lets you specify exactly the data you want to pull instead of just guessing (which will cause issues in the long run).