从Cakephp中的多个表中获取数据

时间:2017-08-11 17:36:50

标签: php mysql cakephp cakephp-2.0

我是cakephp的新手,并尽力在cakephp中实现查询。 我有这个查询

SELECT * FROM question join question_topic on question.question_id=question_topic.question_id join topic on topic.topic_id=question_topic.topic_id join user_topic on user_topic.topic_id=topic.topic_id where user_topic .user_id=10

我在cakephp中需要这个。

我试过的是这个

$this->Behaviors->attach('Containable');
        return $this->find('all', array(

            'contain' => array(
              'User',
              'UserInfo.UserTopic'=>array(
                       'conditions'=>array('UserTopic.user_id'=>10)
                  ),
              'QuestionAndTopic.Topic','UpVoteQuestion','Answer','Answer.UserInfo'

            ),


           'order' => 'rand()',
            'recursive' => 0
        ));

但是查询并没有给我一个正确的结果。你能看一下吗?

Question.php

class Question extends AppModel
{
    public $useTable = 'question';
    public $primaryKey = 'question_id';


    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id',
            'fields' => array('User.user_id','User.email','User.active')

        ),
        'UserInfo' => array(
            'className' => 'UserInfo',
            'foreignKey' => 'user_id',


        )
    );
    public $hasMany = array(
        'Answer' => array(
            'className' => 'Answer',
            'foreignKey' => 'question_id',


        ),

        'QuestionAndTopic' => array(
            'className' => 'QuestionAndTopic',
            'foreignKey' => 'question_id',
     )
  );

  public function latestQuestions(){
         $this->Behaviors->attach('Containable');
        return $this->find('all', array(

            'contain' => array(
              'User',
              'UserInfo.UserTopic'=>array(
                       'conditions'=>array('UserTopic.user_id'=>10)
                  ),
              'QuestionAndTopic.Topic','UpVoteQuestion','Answer','Answer.UserInfo'

            ),


           'order' => 'rand()',
            'recursive' => 0
        ));
    }
}

2 个答案:

答案 0 :(得分:0)

你可以使用Mysql查询它将像cakephp查询一样工作

$this->Behaviors->query('SELECT * FROM question join question_topic on question.question_id=question_topic.question_id join topic on topic.topic_id=question_topic.topic_id join user_topic on user_topic.topic_id=topic.topic_id where user_topic .user_id=10');

答案 1 :(得分:0)

参考this link

    $options['joins'] = array(
    array('table' => 'books_tags',
        'alias' => 'BooksTag',
        'type' => 'inner',
        'conditions' => array(
            'Book.id = BooksTag.book_id'
        )
    ),
    array('table' => 'tags',
        'alias' => 'Tag',
        'type' => 'inner',
        'conditions' => array(
            'BooksTag.tag_id = Tag.id'
        )
    )
);
$options['conditions'] = array(
    'Tag.tag' => 'Novel'
);
$books = $Book->find('all', $options); 

根据你的表和fields.hope进行更改。这有帮助。