【问题标题】:Getting data from a $hasAndBelongsToMany relation at CakePHP 2.2在 CakePHP 2.2 从 $hasAndBelongsToMany 关系中获取数据
【发布时间】:2012-10-17 09:51:42
【问题描述】:

我有 3 张桌子: - 用户 - 帖子 - 订阅(默认为posts_users (n-n))

订阅表是此关系所需的 n-n 表。我不想称它为“posts_users”,因为它对我的系统来说非常混乱,因为我在用户和帖子之间有更多的关系。

为了创建 hasAndBelongsToMany 关系,我这样做了:

帖子(模型):

    public $hasAndBelongsToMany = array(
        'Subscriptions' => array(
                'className' => 'User',
                'joinTable' => 'subscriptions',
                'foreignKey' => 'post_id',
                'associationForeignKey' => 'user_id',
                'unique' => 'keepExisting',
                'conditions' => '',
                'fields' => '',
                'order' => '',
                'limit' => '',
                'offset' => '',
                'finderQuery' => '',
                'deleteQuery' => '',
                'insertQuery' => ''
        )
);

用户(模型):

    public $hasAndBelongsToMany = array(            
    'Post' => array(
        'className' => 'Post',
        'joinTable' => 'subscriptions',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'post_id',
        'unique' => 'keepExisting',
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
        'deleteQuery' => '',
        'insertQuery' => ''
    )
);

假设我想为 id 为 3 的用户查找订阅的帖子。 有什么方法可以find 为用户检索订阅的帖子数据? 我应该在哪个模型中进行查询?怎么样??

谢谢。

【问题讨论】:

    标签: cakephp cakephp-2.0 cakephp-2.1 cakephp-2.2


    【解决方案1】:

    好的。终于明白了。

    您可以从两个相关模型中的任何一个进行查询。在这种情况下,发布用户

    $this->Post->User->find('all', array(
                'conditions' => array('User.id' => $this->Session->read('Auth.User.id')),
                'contain' => array('Subscriptions')
    ));
    

    这将返回当前用户的订阅票(在订阅数组中)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多