Laravel 5.0:如何在数据库的同一列中保存行的多个输入

Laravel 5.0: How to save multiple inputs of rows in the same column of database?

本文关键字:一列 保存 输入 数据库 Laravel      更新时间:2024-01-29

我是Laravel和处理某个问题的绝对初学者。英语不是我的第一语言,所以如果这篇文章对你没有意义,或者你需要更多信息,请留下评论。

我想将多个数据输入插入到数据库表的单列中。

我做了一个页面,里面有一个表格。例如,讲师会在"讲师评论"列的第一行和第二行都留下评论。

然而,我很难找到这样做的方法。我正在处理下面的错误。

如有任何建议,我们将不胜感激。提前感谢!

createblade.php

{!! Form::open(['url' => 'logs']) !!}
<tbody>
  <tr>
    <td class="weeks">
      {!! Form::selectRange('weeks[]', 1, 17) !!}
    </td>
    <td class="work_description">
      {!! Form::textarea('work_description[]', null) !!}
    </td>
    <td class="instructor_comments">
      {!! Form::textarea('instructor_comment[]', null) !!}
    </td>
    <td class="status">
      {!! Form::text('status[]', null) !!}
    </td>
  </tr>
  <tr>
    <td class="weeks">
      {!! Form::selectRange('weeks[]', 1, 17) !!}
    </td>
    <td class="work_description">
      {!! Form::textarea('work_description[]', null) !!}
    </td>
    <td class="instructor_comments">
      {!! Form::textarea('instructor_comment[]', null) !!}
    </td>
    <td class="status">
      {!! Form::text('status[]', null) !!}
    </td>
  </tr>
</tbody>

create_logs_table.php

public function up()
{
    Schema::create('logs', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('weeks');
        $table->text('work_description');
        $table->text('instructor_comments');
        $table->string('status');
        $table->timestamps();
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

错误::

preg_replace():参数不匹配,模式是字符串,而替换是数组

在您的模型中,您可以添加一些有帮助的突变体:

public function setInstructorCommentsAttribute( $value )
{
  $this->attributes['instructor_comments'] = json_encode( $value );
}
public function getInstructorCommentsAttribute()
{
  $type = json_decode( $this->attributes['instructor_comments'] );
  return $type;
}

setInstructorCommentsAttribute将Input数组转换为JSON对象,并将其保存到数据库中。然后getInstructorCommentsAttribute将JSON对象解码回一个数组,供您在代码中使用。

将此代码添加到您的logs模型中。