How do I filter deep associations in CakePHP

前端 未结 4 830
谎友^
谎友^ 2021-01-13 01:24

I have the following tables: binders, docs, users, docs_users. Doc belongsTo Binder, Doc hasAndBelongsToMany User.

I want to get binders and their associated docs f

4条回答
  •  渐次进展
    2021-01-13 02:19

    Have you tried coming in from a user perspective?

    $this->Binder->Doc->User->Behaviors->attach('Containable');
    $this->Binder->Doc->User->contain(array('Doc'=>'Binder'));
    $user = $this->Binder->Doc->User->find('all',array('conditions'=>'User.id'=>$user_id));
    

    The 'DocsUser' association should be detected anyway.

    From a Binders perspective maybe

    In your Binders MODEL add ( please check table, key and model names in case I made a typo )

    function getBindersByUserSql($user_id)
        {       
            $dbo = $this->getDataSource();
            $subQuery = $dbo->buildStatement(
                array(
                        'fields' => array('DISTINCT(Doc.binder_id)'),
                        'table' => "docs_users",                                       
                        'joins' => array(
                                    array('table' => 'users',
                                        'alias' => 'User',
                                        'type' => 'INNER',
                                        'conditions' => array('DocsUser.user_id = User.id')
                                    ),
                                    array('table' => 'docs',
                                        'alias' => 'Doc',
                                        'type' => 'INNER',
                                        'conditions' => array('Doc.id = DocsUser.doc_id')
                                    )
                ),
                        'alias'=>"DocsUser",                                            
                        'conditions' => array("User.id"=>$user_id),
                        'order' => null,
                        'group' => "Doc.binder_id"
                        ),
                        $this
                        );
            return $dbo->expression($subQuery);
        }
    

    Then in your binders CONTROLLER try

    $this->Binder->Behaviors->attach('Containable');
    $this->Binder->contain(array('Doc'));
    $conditions = array();
    $conditions = $this->Binder->getBindersByUserSql($this->Auth->user('id'));
    $binders = $this->Binder->find('all',array('conditions'=>$conditions)));
    

    Any good?

提交回复
热议问题