CakePHP“致命错误:在非对象上调用成员函数getCoalitions()”

时间:2012-05-30 02:52:00

标签: cakephp cakephp-2.1 php

  

可能重复:
  Call to a member function on a non-object

我尝试从CakePHP应用程序中的视图中调用模型中的辅助函数“getColition($ id)”,我收到此错误:

Fatal error: Call to a member function getCoalition() on a non-object
in C:\xampp\htdocs\MyCakeApp\app\View\Candidates\index.ctp on line 32

我认为这可能与普通的MVC有关但我无法弄清楚。应用程序是一个小“选举”应用程序。任何一般辅助功能都会出现类似的问题。

为什么我不能在模型中调用函数?模特是一个辅助功能的适当场所吗?

/app/Model/Candidate.php

<?php
/**
 * @property
 */
class Candidate extends AppModel {
    var $name = 'Candidates';

// THIS I WANT TO CALL
    public function getCoalition($id){
        $results = $this->Candidate->query("SELECT coalitions.name from candidates, coalitions where candidates.coalition_id = coalitions.id and candidates.id =$id");
        return $results;
    }
}
?>

/app/Controller/CandidatesController.php

<?php
class CandidatesController extends AppController {

    public $helpers = array('Html', 'Form');
    public $components = array('Session');
    var $name = 'Candidates';

    public function index() { //index stuff... }
    public function add()  { //add stuff...}
    public function edit($id = null)  { //edit stuff...}
    public function delete($id)  { //delete stuff...}
}
?>

/app/View/Candidate/index.ctp

<h1>Candidates</h1>
<p><?php echo $this->Html->link("Add candidate", array('action' =>'add'), array('class' => 'btn btn-primary')); ?></p>
<hr>
<table>
    <tr>
        <th>Name</th>
        <th>Coalition</th>
    </tr>
<?php foreach ($candidates as $candidate): ?>
    <tr>
        <td><?php echo $candidate['Candidate']['name']; ?></td>
        <td>
            <?php 
///////////////// THIS CREATES THE ERROR ///////////////// 
            echo $this->Candidate->getCoalition($candidate['Candidate']['coalition_id']);
            ?>
        </td>
        <td><?php 
        echo $candidate['Candidate']['votes'];
        echo $this->Html->link('Muokkaa', array('action' => 'edit', $candidate['Candidate']['id'])); 
         ?>    
    </td>
    </tr>
<?php endforeach; ?>
</table>

2 个答案:

答案 0 :(得分:4)

您无法在视图中使用模型。您需要做的是从Controller设置视图var。

仔细观察您正在做的事情,您只需要增加递归级别,以便返回带有候选记录的Colition数据或使用Containable。

$this->Candidate->find('all', array('conditions' => ..., 'recursive' => 2));

添加public $ actsAs = array(&#39; Containable&#39;);到AppModel和

$this->Candidate->find('all', array('conditions' => ..., 'contain' => array('Colition'));

候选人和Colition之间有什么关系?

答案 1 :(得分:0)

是表/字段

  

来自候选人,联盟的coalitions.name

存在于数据库中?