我已经在两个表(书籍和作者)之间设置了一个hasmany关联。关联正常工作,但尝试检索属于一本书的所有作者时除外。如果我这样做
$book = $this->Book->findById($id)
返回的数组将没有数组作者;它将具有 AuthorToBook 联接模型信息,但它不会自动获取与其关联的作者。
我必须将递归设置为 2 才能检索连接模型和关联的作者。我还在重新获取每个AuthorToBook关联的书籍数据。
'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'
)
)
)
现在的问题是 - 如何在不设置递归参数的情况下获取由 hasMany Through 关系形成的关联模型?
这是来源
<?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');
}
?>
可包含的行为是你的朋友,是递归的替代品。 它允许您准确指定要通过每个查询检索的关联模型。
递归是一件很酷的事情,但人们几乎同意,除了做 CakePHP 的介绍教程之外,你不应该实际使用它。 在您的 AppModel 中设置public $recursive = -1;
(默认情况下会将其关闭),并且永远不要回头。