2012-11-08 10 views
1

我想在第二個表中添加數據的函數中調用函數時,我想在一個控制器文件中添加兩個表中的數據.. error error:調用成員函數保存()非對象想要在CakePhp中使用一個控制器文件在兩個表中插入數據

下面就爲我的控制器文件

<?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.'); 
      } 
     } 
    } 

} 
?> 

回答

0

變量$使用=陣列(「主型號名稱」,「第二屆型號名稱」 ......等等);

如:

<?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) 

} 
?> 
+0

感謝您的回覆...我嘗試了那個..並且創建了模型文件名city.php並且還在db中創建了一個名爲cities的表,但是這次出現了一個錯誤Notice(8):Array to string conversion [CORE /Cake/Model/Datasource/DboSource.php,line 459] –

+0

請檢查您的輸入值 – Elby

+0

ya其作品..現在我試着用自己的自定義函數..現在我試着用save()它的作品...非常感謝..! 您能否讓我知道我們可以在cakePHp中爲db編寫自定義查詢? –

1

您可以使用模型鏈接。我假設城市和國家是相關的(也許是一箇中間模型的國家?)。

所以這將是$this->Country->City->save()$this->Country->IntermediaryModel->City->save()取決於你的關係。

相關問題