0

我正在使用https://github.com/Maatwebsite/Laravel-Excel这个包。当我上传我的文件和 dd(result) 是

    CellCollection {#842 ▼

         #title: null
        #items: array:4 [▼
         "news_title" => "7th AGM of ADBL today; endorsing 47% cash"            
         "desc" => "The AGM will be endorsing 47% percent cash dividend to its shareholders from the net profit it earned in last fiscal year 2070/71. "
            "link" => "http://www.sharesansar.com/viewnews.php?id=26224&cat=news"
         "stock_code" => "LBL"
        ]
    }

所以,这里#items 包含我的数据,而我不知道为什么要输出#title。当我尝试存储我的数据时,由于这个#title,我收到了完整性违规错误?那么,有解决办法吗?

这是我存储数据的代码

     public function excelNews()
    {
        if (Input::hasFile('file')) {
            $file = Input::file('file');
            Excel::load($file, function($reader) {
                $reader->setDateFormat('j/n/Y H:i:s');
                $results = $reader->get();
                 foreach ($results as $result)
                {
                    dd($result); // for testing
                    $news = new StockNews;
                    $news->title = $result->news_title;
                    $news->desc = $result->desc;
                    $news->save()
                }

         });
    }
        Flash::success('News has been successfully updated');
        return redirect::back();
    }

错误信息

完整性约束违规列“标题”不能为空

4

1 回答 1

1

发生错误是因为标题为空并尝试将其保存到数据库。

有2种方法可以解决问题

在迁移中,将列设置为可为空

$table->string('title')->nullable();

来源: http: //laravel.com/docs/4.2/schema#adding-columns

或检查值,如果它为空,则将标题设置为空字符串

$news->title = ($result->news_title) ? $result->news_title : '' ;
于 2015-04-10T06:36:12.557 回答