【问题标题】:Saving Array to Database in CakePHP在 CakePHP 中将数组保存到数据库
【发布时间】:2010-12-06 19:29:08
【问题描述】:

我没办法了,这是我的控制器:

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

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

【问题讨论】:

    标签: arrays cakephp model controller


    【解决方案1】:

    如果我正确理解您的要求,以下应该可以工作。

    在您的控制器中:

    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。

    【讨论】:

    • 非常感谢,现在明白了,很有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多