2014-09-19 72 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选择(慢),将做计数或做的结果是缓慢和不准确的过滤。