2014-09-19 73 views
0

我已經設置了簡單的關聯,例如作者有很多書和一本書屬於作者。我的文件如下。只獲得父母在cakephp協會中有孩子

<?php 
class Author extends AppModel 
{ 
    var $name = 'Author'; 
    var $hasMany = 'Book'; 
} 
?> 

<?php 
class Book extends AppModel 
{ var $name = 'Book'; 
    var $belongsTo = 'Author'; 
} 
?> 


<?php 
class AuthorsController extends AppController { 
    var $name = 'Authors'; 

    public function index(){ 
    $authors=$this->Author->find('all'); 
    pr($authors);die; 
} 

} 
?> 

當我寫pr($ authors);它會打印作者表的所有數據。

Array 
(
    [0] => Array 
     (
      [Author] => Array 
       (
        [id] => 1 
        [name] => Jack 
        [email] => [email protected] 
        [website] => www.Jack.com 
       ) 

      [Book] => Array 
       (
        [0] => Array 
         (
          [id] => 1 
          [isbn] => a12sdsdsd 
          [title] => Book One 
          [description] => Description One 
          [author_id] => 1 
         ) 

        [1] => Array 
         (
          [id] => 2 
          [isbn] => fgg234234 
          [title] => Book Two 
          [description] => Description Two 
          [author_id] => 1 
         ) 

       ) 

     ) 

    [1] => Array 
     (
      [Author] => Array 
       (
        [id] => 2 
        [name] => Ron 
        [email] => [email protected] 
        [website] => www.Ron.com 
       ) 

      [Book] => Array 
       (
       ) 

     ) 

) 

正如你所看到的,作者(Ron)的id:2沒有書。因此本書陣列empty.What我想是讓只有那些有任何一本書(這裏只作家傑克數據應退還)。如何做到這一點的作者我在閱讀中可容納的行爲:

http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

但是沒有這樣的選擇來實現這一點。任何幫助,將不勝感激。

在此先感謝!

回答

0

我有一個類似的問題的,這是我解決的方式,它的骯髒,但在CakePHP 1.3我找不到更好的解決辦法

你也可以試着做了$這個 - >查詢與具有

//Inside model 
     $authors = $this->find('all', array(
     'fields' => $fields, 
     'conditions' => $conditions, 
     'order' => 'id asc', 
     'contain'=>array(
      'Book' => array(
       'conditions'=> $bookConditions, 
       ), 
      ) 
     ) 
    ); 

    //We don't want the results without books 
    foreach($authors as $index => $author){ 
     if((!$author['Book'])){ 
      unset($authors[$index]); 
     } 
    } 

    return $authors; 
+0

這將不適用於分頁,它總體上是一個非常緩慢的解決方案,不會導致準確的結果,當期待10但未被設置6。 – burzum 2014-09-19 13:20:26

0

實現一個counter cache,讓你得到你可以然後只需通過這個條件找到authors表書的數量(型號代碼):

array($this->alias . '.book_count > 0'); 

計數呃緩存刪除需要有SQL選擇(慢),將做計數或做的結果是緩慢和不準確的過濾。