在CakePHP中将数组保存到数据库

时间:2010-12-06 19:29:09

标签: arrays cakephp model controller

我的想法是我的控制器:

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'));

我正在阅读“GoogleNews”中的数据,他们在我的阵列中。数组看起来像这样:

  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')));

这是一个解决方案吗? 它唯一的工作方式,但它将空值放入我的列。

1 个答案:

答案 0 :(得分: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。