【问题标题】:Laravel 5.0: How to save multiple inputs of rows in the same column of database?Laravel 5.0:如何在数据库的同一列中保存多个行的输入?
【发布时间】:2016-04-06 19:28:50
【问题描述】:

我是 Laravel 的绝对初学者,并且正在处理某个问题。 英语不是我的母语,所以如果这篇文章对您没有意义或者您需要更多信息,请离开 cmets。

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

我做了一个页面,里面有一个表格。例如,讲师将在第一行和第二行的“讲师评论”列中留下 cmets。

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

任何建议将不胜感激。提前致谢!

create.blade.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():参数不匹配,pattern是字符串,replacement是数组

【问题讨论】:

  • 您的错误发生在您在代码中某处调用 preg_replace() 的地方,而这不是您在上面粘贴的代码。您是否有用于从表单获取信息并将其保存到您可以粘贴的数据库的控制器的代码?

标签: javascript php laravel-5


【解决方案1】:

在您的模型中,您可以添加一些可以提供帮助的修改器:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 2018-12-17
    相关资源
    最近更新 更多