我试图在书籍和作者之间建立一个很多关联,但是当从数据库中提取作者的书籍时,他们会在书籍和作者之间建立起来。属性永远不会定义。给我以下错误:
Warning (2): Invalid argument supplied for foreach() [APP/Template\Authors\index.ctp, line 6]
到目前为止我的代码:
的src /型号/ Authors.php
<?php
class Author extends AppModel
{
var $name = 'Author';
var $hasMany = 'Book';
}
?>
的src /型号/ Books.php
<?php
class Book extends AppModel
{ var $name = 'Book';
var $belongsTo = 'Author';
}
?>
SRC /控制器/ BooksController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
class BooksController extends AppController {
var $name = 'Books';
function index() {
$this->Book->recursive = 1;
$books = $this->Book->find('all');
$this->set('books', $books);
}
}
?>
SRC /控制器/ AuthorsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
class AuthorsController extends AppController {
var $name = 'Authors';
function index() {
$this->Authors->recursive = 2;
$authors = $this->Authors->find('all');
$this->set('authors', $authors);
}
}
?>
的src /模板/作者/ index.php的
<?php foreach($authors as $author): ?>
<h2><?php echo $author['Author']['name'] ?></h2>
<hr />
<h3>Book(s):</h3>
<ul>
<?php foreach($author['Book'] as $book): ?>
<li><?php echo $book['title'] ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
数据库作者和书籍表都包含数据,并使用以下迁移创建:
<?php
use Migrations\AbstractMigration;
class CreateAuthors extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function change()
{
$table = $this->table('authors');
$table->addColumn('name', 'text', [
'default' => null,
'null' => false,
]);
$table->addColumn('email', 'text', [
'default' => null,
'null' => false,
]);
$table->addColumn('website', 'text', [
'default' => null,
'null' => false,
]);
$table->create();
}
}
并且
<?php
use Migrations\AbstractMigration;
class CreateBooks extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function change()
{
$table = $this->table('books');
$table->addColumn('isbn', 'text', [
'default' => null,
'null' => false,
]);
$table->addColumn('title', 'text', [
'default' => null,
'null' => false,
]);
$table->addColumn('description', 'text', [
'default' => null,
'null' => false,
]);
$table->addColumn('author_id', 'string', [
'default' => null,
'limit' => 255,
'null' => false,
]);
$table->create();
}
}
非常感谢任何帮助。