只有父母在cakephp协会中有孩子

时间:2014-09-19 10:11:46

标签: cakephp associations

我设置了简单的关联,例如,作者有很多书,一本书属于作者。我的文件如下。

<?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] => test@test.com
                    [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] => demo@demo.com
                    [website] => www.Ron.com
                )

            [Book] => Array
                (
                )

        )

)

如您所见,作者(Ron)的身份证号码为2,没有书。所以Book数组是空的。我想要的只是那些作者有任何书(这里只有作者杰克数据应该被退回)。如何实现这一点?我已经阅读了关于可容纳行为的信息:

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

但是没有这样的选择来实现这一点。任何帮助都将受到赞赏。

提前致谢!

2 个答案:

答案 0 :(得分:0)

我有一个类似的问题,这是我解决它的方式,它很脏但我在CakePhp 1.3中找不到更好的解决方案

您还可以尝试使用

进行$ this-&gt;查询
//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;

答案 1 :(得分:0)

实施counter cache以便您获得作者表中的书籍数量,然后您可以根据此条件(模型代码)找到它们:

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

计数器缓存消除了在SQL(缓慢)中进行子选择的需要,这些子选择将进行计数或对结果进行过滤,这是缓慢且不准确的。

相关问题