2010-12-06 66 views
2

我的想法,這裏是我的控制器:從「了Googlenews」數組保存到數據庫中的CakePHP

class GoogleNewsController extends AppController { 
    var $name = 'GoogleNews'; 
    var $uses = array('GoogleNews', 'SavedNews'); 
    var $helpers = array('Html','Form'); 
    function index() { 

$saved = $this->set('news',$this->GoogleNews->find('all')); 

即時閱讀數據和他們在我的數組。數組是這樣的:

array(10) { 
    [0]=> 
    array(1) { 
    ["GoogleNews"]=> 
    array(12) { 
     ["title"]=> 
     string(32) "FIFA 11 für 25,49€ aus Jersey" 
     ["link"]=> 
     string(54) "http://feedproxy.google.com/~r/myDealZ/~3/HuNxRhQJraQ/" 
     ["pubDate"]=> 
     string(31) "Mon, 06 Dec 2010 10:53:22 +0000" 
     ["creator"]=> 
     string(5) "admin" 
     ["guid"]=> 
     array(2) { 
     ["value"]=> 
    string(30) "http://www.mydealz.de/?p=15137" 
    ["isPermaLink"]=> 
    string(5) "false" 
    } 
    ["description"]=> 
    string(355) " 

我想保存元素,我的數據庫「SavedNews」 我需要保存的說明和標題。 有人可以告訴我該怎麼寫嗎?

$this->SavedNews->set(array('description' =>$this->GoogleNews->find('description'))); 

這是一個解決方案嗎? 它的工作原理是唯一的方式,但它將空值添加到我的列中。

回答

4

如果我正確理解您的要求,以下應該工作。

在你的控制器:

class NewsController extends AppController 
{ 
    function import_from_google() 
    { 
     // Load the GoogleNews model and retrieve a set of its records 
     $this->loadModel('GoogleNews'); 
     $newsFromGoogle = $this->GoogleNews->find('all'); 

     $this->loadModel('SavedNews'); 
     foreach ($newsFromGoogle as $_one) { 

      // Reset the SavedNews model in preparation for an iterated save 
      $this->SavedNews->create(); 

      // Assemble an array of input data appropriate for Model::save() 
      // from the current GoogleNews row 
      $saveable = array(
       'SavedNews' => array(
       'title' => $_one['GoogleNews']['title'], 
       'description' => $_one['GoogleNews']['description'] 
      ) 
      ); 

      // send the array off to the model to be saved 
      $this->SavedNews->save($saveable); 
     } 

     $this->autoRender = false; // No need to render a view 
    } 
} 

提純所期望/需要。例如,迭代的保存操作應該發生在SavedNews模型中,而不是在控制器中。上面的代碼也沒有容錯功能。

HTH。

+0

非常感謝,現在我明白了,這非常有幫助 – Jasiufila 2010-12-07 08:03:45