繁体   English   中英

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

[英]Want to insert data in two tables using one controller file in 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.');
            }
        }
    }

}
?>

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

因此,取决于您的关系,它应该是$this->Country->City->save()$this->Country->IntermediaryModel->City->save()

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)

}
?>  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM