如何修复 注意 (8):未定义的变量:cakePHP 中的书籍 [APP/Templatebooksindex.



我完全是使用CakePhp的新手。我已经解决了我的一些问题,但我又遇到了这个基本问题。你能帮我解决这个问题吗?

Notice (8): Undefined variable: books [APP/Templatebooksindex.ctp, line 6]
Warning (2): Invalid argument supplied for foreach() [APP/Templatebooksindex.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 AppController;
 use AppControllerAppController;
 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');
  }
 }
 ?>

这是我的书.php:

<?php
 /**
 * @property books $books
 */
  class books extends AppModel
  {  
    var $name = 'books';
    var $belongsTo = 'authors';
  }
  ?>

您需要像这样从显示方法中获取索引方法

<?php
   /**
   * @property BooksController $BooksController
   */
    namespace AppController;
    use AppControllerAppController;
    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');
       }
   }
?>

你应该这样编写控制器代码

 <?php
 namespace AppController;
 use AppControllerAppController;
 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>

最新更新