doutenggu4070
2016-02-02 02:03 阅读 100
已采纳

laravel foreach循环只存储db表中数组的最后一个元素

i have function in my controller that uses php excel to read rows from excel file, and store it to db table.

public function processData(Request $request)
{
    /* store data from form in to variables */
    $hotel = $request->input('hotel');
    $date = $request->input('date');
    $start_row = $request->input('row');
    $date_col = $request->input('date-col');
    $sold_col = $request->input('sold-col');
    $rev_col = $request->input('rev-col');

    /* get tables name */
    $table = str_replace('-', '_', $hotel);
    $monthly_table = $table . '_monthly';

    /* init hotel class */
    $hotel_table = new Hotel($table);

    $file = public_path().'/'.$date.'.xls';

    $sheetData = Excel::load($file)->noHeading()->getExcel()->getSheet()->toArray(null,false,false, true);
    $sheetData = array_slice($sheetData, $start_row - 1);

    foreach ($sheetData as $row)
    {
        if ($this->isDate($row[$date_col]))
        {
            print $row[$date_col] . "---" . $row[$sold_col] . "---" . gettype(money_format('%i', floatval($row[$rev_col]))) . "<br>";
            $hotel_table->date = $row[$date_col];
            $hotel_table->sold = intval($row[$sold_col]);
            $hotel_table->sold_diff = 0;
            $hotel_table->rev = floatval($row[$rev_col]);
            $hotel_table->rev_diff = 0;
            $hotel_table->row = $start_row;
            $hotel_table->date_col = $date_col;
            $hotel_table->sold_col = $sold_col;
            $hotel_table->rev_col = $rev_col;
            //$hotel_table->save();
            if (!$hotel_table->save())
            {
                dd ( DB::getQueryLog() );
            }

        }
    }

}

public function isDate($date)
{
    if (date('m/d/Y', strtotime($date)) == $date)
    {
        return true;
    }
    else
    {
        return false;
    }
}

this is my table

Schema::create($tableName, function (Blueprint $table) {
            $table->increments('id');
            $table->string('date');
            $table->integer('sold');
            $table->integer('sold_diff');
            $table->float('rev');
            $table->float('rev_diff');
            $table->string('row');
            $table->string('date_col');
            $table->string('sold_col');
            $table->string('rev_col');
            $table->timestamps();
        });

when i go thru the foreach its printing things just fine to the screen there are no errors, but when i look at the table it only has last element of the array in db table.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanjiagu0655 duanjiagu0655 2016-02-02 02:09

    If Hotel class is your model then you need to move following code inside foreach block

    foreach ($sheetData as $row)
    {
        if ($this->isDate($row[$date_col]))
        {           
           $hotel_table = new Hotel($table);
           ...
        }
    }
    
    点赞 评论 复制链接分享

相关推荐