想要使用CakePhp中的一个控制器文件在两个表中插入数据

时间:2012-11-08 06:07:13

标签: php cakephp

当我调用函数在第二个表中添加数据时,我想在两个表中添加数据形成一个控制器文件..错误来了:在非对象上调用成员函数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.');
            }
        }
    }

}
?>

2 个答案:

答案 0 :(得分:1)

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

根据您的关系,它会是$this->Country->City->save()$this->Country->IntermediaryModel->City->save()

答案 1 :(得分: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)

}
?>