CodeIgniter-未定义的属性错误


CodeIgniter - Undefined Property Error

我正试图访问表中的所有波段,并将它们打印在列表中,但当我运行它时,我会收到以下错误:

Severity: Notice
Message: Undefined property: CI_Loader::$model_bands
Filename: views/band_view.php
Line Number: 16

band_view.php:

<h3>List of Bands:</h3>
<?php
$bands = $this->model_bands->getAllBands();
echo $bands;
?>

model_bands.hp:

function getAllBands() {
    $query = $this->db->query('SELECT band_name FROM bands');
    return $query->result();    
}

有人能告诉我为什么要这么做吗?

为什么需要这样做,正确的方法是在控制器内部使用模型方法,然后将其传递到视图:

public function controller_name()
{
    $data = array();
    $this->load->model('Model_bands'); // load the model
    $bands = $this->model_bands->getAllBands(); // use the method
    $data['bands'] = $bands; // put it inside a parent array
    $this->load->view('view_name', $data); // load the gathered data into the view
}

然后在视图中使用$bands(循环)。

<h3>List of Bands:</h3>
<?php foreach($bands as $band): ?>
    <p><?php echo $band->band_name; ?></p><br/>
<?php endforeach; ?>

您在控制器中加载了模型吗?

    $this->load->model("model_bands");

您需要像控制器

public function AllBrands() 
{
    $data = array();
    $this->load->model('model_bands'); // load the model
    $bands = $this->model_bands->getAllBands(); // use the method
    $data['bands'] = $bands; // put it inside a parent array
    $this->load->view('band_view', $data); // load the gathered data into the view
}

然后查看

<h3>List of Bands:</h3>
<?php foreach($bands as $band){ ?>
    <p><?php echo $band->band_name; ?></p><br/>
<?php } ?>

你的型号还可以

function getAllBands() {
    $query = $this->db->query('SELECT band_name FROM bands');
    return $query->result();    
}

您忘记在控制器上加载模型:

//controller
function __construct()
{
    $this->load->model('model_bands'); // load the model
}

顺便说一句,你为什么直接从你的角度调用模型?应该是:

//model
$bands = $this->model_bands->getAllBands();
$this->load->view('band_view', array('bands' => $bands));
//view
<h3>List of Bands:</h3>
<?php echo $bands;?>