我完全是使用CakePhp的新人。我已经解决了我的一些问题,但是我再次遇到了这个基本问题。你能帮我解决这个问题。
Notice (8): Undefined variable: books [APP/Template\books\index.ctp, line 6]
Warning (2): Invalid argument supplied for foreach() [APP/Template\books\index.ctp, line 6]
这是错误消息指出的代码:
<table>
<thead>
<th>ISBN</th><th>Title</th><th>Author</th>
</thead>
<?php foreach($books as $book): ?>
<tr>
<td><?php echo $book['books']['isbn'] ?></td>
<td><?php echo $book['books']['title'] ?></td>
<td><?php echo $book['authors']['name'] ?></td>
</tr>
<?php endforeach; ?>
</table>
这是我的BooksController.php:
<?php
/**
* @property BooksController $BooksController
*/
namespace App\Controller;
use App\Controller\AppController;
class BooksController extends AppController {
public function display()
{
function index() {
$this->books->recursive = 1;
$books = $this->books->find('all');
$this->set('books', $books);
}
$this->render('index');
}
}
?>
这是我的books.php:
<?php
/**
* @property books $books
*/
class books extends AppModel
{
var $name = 'books';
var $belongsTo = 'authors';
}
?>
答案 0 :(得分:1)
你需要从这个
这样的显示方法中获取索引方法<?php
/**
* @property BooksController $BooksController
*/
namespace App\Controller;
use App\Controller\AppController;
class BooksController extends AppController {
public function display()
{
}
function index() {
$this->books->recursive = 1;
$books = $this->books->find('all');
$this->set('books', $books);
$this->render('index');
}
}
?>
答案 1 :(得分:0)
您应该以这种方式编写控制器代码
<?php
namespace App\Controller;
use App\Controller\AppController;
class BooksController extends AppController {
public function index()
{
$this->books->recursive = 1;
$books = $this->books->find('all');
$this->set('books', $books);
$this->render('index');
}
}
您的查看文件代码是:
<table>
<thead>
<th>ISBN</th><th>Title</th><th>Author</th>
</thead>
<?php foreach($books as $key => $book){ ?>
<tr>
<td><?php echo $book['books']['isbn'] ?></td>
<td><?php echo $book['books']['title'] ?></td>
<td><?php echo $book['authors']['name'] ?></td>
</tr>
<?php } ?>
</table>