Retrieving the associated model in a hasMany through association without recursive

StackOverflow https://stackoverflow.com/questions/22129857

  •  19-10-2022
  •  | 
  •  

質問

I have set up a hasMany through association between two tables - Books and Authors. The associations work properly, except when attempting to retrieve all the authors that belongs to a book. If I do this

$book = $this->Book->findById($id)

The array returned will not have an array Authors; it will have the AuthorToBook join model information, but it won't automatically fetch the Author associated with it.

I have to set recursive to 2 in order to retrieve the join model, and the associated Author. I am also re-fetching the Book data for each AuthorToBook association there is.

'AuthorToBook' => array(
        (int) 0 => array(
            'id' => '1',
            'author_id' => '1',
            'book_id' => '2',
            'Author' => array(
                'id' => '1',
                'name' => 'J.R.R Tolkien',
                'date_of_birth' => '1892-01-03 00:00:00',
                'bio' => 'Professor and inventor of the Elvish Language'
            ),
            'Book' => array(
                'id' => '2',
                'title' => 'Return of the King',
                'pagecount' => '1200',
                'publisher_id' => '1'
            )
        )
    )

Now the question is - how can I fetch the associated model formed with a hasMany Through relationship without setting the recursive parameter?

Here's the source

<?php
class Author extends AppModel
{
    public $hasMany = array('AuthorToBook');
}
?>

<?php
class AuthorToBook extends AppModel 
{
    public $useTable = 'authors_to_books';
    public $belongsTo = array('Author', 'Book');
}
?>

<?php
class Book extends AppModel {


    public $hasMany = array('AuthorToBook');

}
?>
役に立ちましたか?

解決

Containable Behavior is your friend and is THE replacement for recursive. It allows you to specify exactly which associated model(s) you want to retrieve with each query.

Recursive is a cool thing, but it's pretty much agreed that you shouldn't actually use it beyond doing the intro tutorial for CakePHP. Set public $recursive = -1; in your AppModel (which makes it off by default), and never look back.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top