1

当我调用函数以在第二个表中添加数据时,我想从一个控制器文件中的两个表中添加数据..错误出现错误:调用非对象上的成员函数 save()

这是我的控制器文件

<?php
class CountryController extends AppController {
    var $name = 'Country';
    var $helpers = array('Html', 'Form' );


    // called index function 
    public function index() {
        $this->render();
    }

    // Function for add countries in database
    public function addCountry() {
        if (empty($this->data)) {
            $this->render();
        } else {
        //  $this->cleanUpFields();
            if ($this->Country->save($this->data)) {
                $this->Session->setFlash('The Counrty has been saved');
                $this->redirect('/country/index');
            } else {
                $this->Session->setFlash('Please correct errors below.');
            }
        }
    }

    public function addCity() {
        $cities = $this->set('country', $this->Country->find('all'));
        $this->set(compact('cities'));
        if(empty($this->data)){
            $this->render();
        } else {
            print_r($this->data);// die();
            if ($this->City->save($this->data)) {
                $this->Session->setFlash('The City has been saved');
                $this->redirect('/country/index');
            } else {
                $this->Session->setFlash('Please correct errors below.');
            }
        }
    }

}
?>
4

2 回答 2

1

您可以使用模型链接。我假设一个城市和国家是相关的(也许是一个中间模型国家?)。

所以这将是$this->Country->City->save()$this->Country->IntermediaryModel->City->save()取决于你的关系。

于 2012-11-08T06:14:13.867 回答
0

var $uses = array('主要型号名称' , '第二型号名称' .......等等);

例如:

<?php
class CountryController extends AppController {
    var $name = 'Country';
    var $helpers = array('Html', 'Form' );
    // $uses is where you specify which models this controller uses
    var $uses = array('Country', 'City');

    // ... here go your controller actions (methods)

}
?>  
于 2012-11-08T06:09:52.140 回答