2014-01-09 80 views
0

我想獲取記錄表格2模型(Booking和Message),兩種模型都沒有任何關係。從cakephp中的一個模型加入兩個模型

我嘗試了很多,但它不工作 我使用的代碼(http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables

$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); 

回答

0

試試這個:

BookModel:

public $hasMany = array(
    'BooksTag' => array(
     'foreignKey' => 'book_id' 
    ) 
); 

TagModel:

public $hasMany = array(
    'BooksTag' => array(
     'foreignKey' => 'tag_id' 
    ) 
); 

BooksController:

$this->Book->Behaviors->load('Containable'); 
$this->Book->find('all', array(
    'contain' => array(
     'BooksTag' => array(
      'Tag', 
     ), 
    ), 
)); 
0

我更喜歡在許多查詢中這樣做。首先找到所需要的標籤:

$this->loadModel('Tag'); 
    $tag = $this->Tag->find('first', array('conditions' => array('Tag.tag' => 'Novel'))); 
    $tag_id = $tag['Tag']['id']; 

然後找book_ids

$this->loadModel('BookTag'); 
    $book_ids = $this->BookTag->find('list', array('conditions' => 'BookTag.tag_id' => $tag_id, 'fields' => 'book_id, book_id')); 

然後找書:

$this->Book->find('all', array('conditions' => array('Book.id' => $book_ids))); 

這是一個漫長的代碼,但運行速度快,易於理解。另一種方法是使用子查詢,但它們很醜並且可能會減慢應用程序的速度