2017-08-11 66 views
0

我是cakephp中的新人,並且盡我所能在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 
     )); 
    } 
} 

回答

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'); 
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這有助於。