dqmdlo9674 2014-02-16 20:08 采纳率: 100%
浏览 10

查找HABTM模型关联是否已存在

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!

  • 写回答

1条回答 默认 最新

  • dousong9729 2014-02-16 21:06
    关注

    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).

    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题