2010-12-06 65 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