Skip to main content
 首页 » 编程设计

php之Kohana View之循环 find_all()

2023年09月27日54oomusou

我是一个非常新的尝试一些 kohana 代码的人,并且已经遇到了第一个问题:(

为了快速起见,这是我的模型

<?php 
 
class Model_Post extends ORM { 
 
} 

这是我的 Controller

<?php defined('SYSPATH') or die('No direct script access.'); 
 
class Controller_Blog extends Controller { 
 
    public function action_index() 
    { 
        $posts = ORM::factory('Post')->find_all(); 
        $view = View::factory('blog/index') 
            ->bind('posts', $posts);  
        $this->response->body($view); 
    } 
} // End Blog 

这是我的观点

<h2>My list of blog posts</h2> 
<? foreach($posts as $post): ?> 
    <hr /> 
    <h4><?= $post->author ?></h4> 
    <p><?= $post->body ?></p> 
<?endforeach; ?> 

现在我收到错误

ErrorException [ Notice ]: Undefined variable: post 
APPPATH\views\blog\index.php [ 4 ] 
1 <h2>My list of blog posts</h2> 
2 <? forech($posts as $post): ?> 
3   <hr /> 
4   <h4><?= $post->author ?></h4> 
5   <p><?= $post->body ?></p> 
6 <?endforeach; ?> 

我正在经历this video

当我将 Controller 更改为时,我的结果集不为空

class Controller_Blog extends Controller { 
 
    public function action_index() 
    { 
        $posts = ORM::factory('Post')->find_all(); 
    //  $view = View::factory('blog/index') 
    //      ->bind('posts', $posts);  
        $this->response->body($posts[0]->body); 
    } 
} // End Blog 

它显示了我的第一行

请您参考如下方法:

我也有同样的问题!我尝试像这样更改index.php:

<h2>My list of blog posts</h2> 
 
<?php foreach($posts as $post): ?> 
    <hr /> 
    <h4><?php echo $post->author ?></h4> 
    <p><?php echo $post->body ?></p> 
<?php endforeach; ?> 

它对我有用!