2013-02-13 40 views
1

在cakephp 1.2中,我有一個帶書籍列表的表格(biblio),和另一個表格(tematiche),我在這裏列出標籤。
我有這樣的代碼來獲取圖書列表:
SQL Query CakePHP 1.2來自2個不同的表格

if (isset($autore_diviso)) 
     { 
      $dim=count($autore_diviso); 
      $i=0; 
      while ($i<$dim) 
      { 
       $conditions[]=array ('autori LIKE ?' => array(
        '%' . $autore_diviso[$i][0] . '%')); 
       $i++; 
      } 
     } 
     else 
      $conditions[]=array('autori LIKE' => "%$a%"); 
     if (!$anno&&!$anno2) // Da sistemare. 
      $conditions=$conditions; 
     else { 
     if (!$anno) 
      $conditions[] = array('anno <=' => "$anno2");   
     if (!$anno2) 
      $conditions[] = array('anno >=' => "$anno"); 
     } 
     if ($anno&&$anno2) 
      $conditions[] = array('anno BETWEEN ? AND ?' => array($anno,$anno2)); } 


現在我也需要得到一本書的標籤,我怎樣才能把它添加到這個查詢?

+0

的結果,嘗試在兩表有關係嗎? – 2013-02-13 08:23:24

+0

在標籤表中有書籍編號 – Ettore 2013-02-13 08:28:07

+0

您是否定義了模型中的關係? – 2013-02-13 08:30:04

回答

1

結合Tag model在控制器

在控制器

<?php 

$this->Book->bindModel(array 
(
    'hasMany' => array 
    (
     'Tag' => array 
     (
      'foreignKey' => false, 
      'conditions' => array 
      (
       'Book.id = Tag.book_id' 
      ) 
     ) 
    ) 
)); 

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

pr($books); 
exit;

上述調試

Array 
(
    [Book] => Array 
    (
     [id] => SOMEID 
     [name] => BOOKNAME 
    ) 
    [Tag] => Array 
    (
     [0] => Array 
     (
      [id] => 1 
      [name] => TAGNAME 
      [book_id] => SOME_ID 
     ) 
     [1] => Array 
     (
      [id] => 2 
      [name] => TAGNAME 
      [book_id] => SOME_ID 
     ) 
     [2] => Array 
     (
      [id] => 4 
      [name] => TAGNAME 
      [book_id] => SOME_ID 
     ) 
    ) 
)
+0

謝謝,我會嘗試 – Ettore 2013-02-13 09:04:52

+0

好運...... :) – 2013-02-13 09:05:34