【问题标题】:How to pass category ID to form post如何传递类别 ID 以形成帖子
【发布时间】:2021-10-31 10:27:07
【问题描述】:

我只是 re-structured my database 有一个 category 表,而不是在我的主窗体上使用类别列。如何将category_id 传递给我的表单,以便我的表单正确发布?现在我收到了这个错误,我相信这是因为我的category_id 是整数类型并且我正在提交一个字符串。

SQLSTATE[22007]:日期时间格式无效:1366 整数值不正确

我还通过 PHPMYADMIN 手动将 Comp Time UsedOT AccruedSick TimeVacation Time Used 插入到我的 category 表中。有一个更好的方法吗?可能在我的模型中?

我有一个如下所示的表单

<div class="form-group">
    <label for="categoryForm">Category:</label>
    <select class="form-control" name="category_id" id="categoryForm" placeholder="Category">
      <option name="category_id">Comp Time Used</option>
      <option name="category_id">OT Accrued</option>
      <option name="category_id">Sick Time</option>
      <option name="category_id">Vacation Time Used</option>
    </select>
</div>

我的表单迁移如下所示:

Schema::create('times', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id');
    $table->date('start_day');
    $table->unsignedBigInteger('category_id');
    $table->time('start_time');
    $table->time('finish_time');
    $table->time('duration');
    $table->text('notes');
    $table->timestamps();

    $table->foreign('user_id')->references('id')->on('users');
    $table->foreign('category_id')->references('id')->on('categories');

});

我的类别表的迁移

public function up() {
    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->timestamps();
        $table->string('type');
    });
}

【问题讨论】:

  • 您想在下拉列表中显示虚假数据,还是只想从表单中将数据插入db
  • 问题不在于category_id,而在于start_date,您传递的是整数而不是日期时间。此外,您不必在每个选项上添加name="category_id",只需将其添加到选择...
  • 我已经发布了一个答案,name 的属性与&lt;option&gt; 不匹配,如果您希望后端访问它,请始终使用value

标签: php laravel eloquent


【解决方案1】:

假设您想将一个数组从控制器传递到 laravel 中刀片视图上的表单。

你的 Controller 方法应该是这样的。

use App\Category; //import model
public function create()
{
   $categories = Category::all();
   return view('folder.bladefile', compact('categories')); //by this you will be able to access categories in your bladefile.
}

在你的刀片文件中,你可以做这样的事情

<select class="form-control" name="category_id" id="categoryForm" placeholder="Category">
   @foreach($categories as $category)
     <option value="{{$category->id}}">{{$category->name}}</option>
   @endforeach;
</select>

【讨论】:

    【解决方案2】:

    问题不在于category_id,而在于start_date,您传递的是整数而不是日期时间,正如它所说的错误。

    此外,在每个选项上添加name="category_id" 是不正确的,您必须将其添加到选择中。

    在您的&lt;option&gt; 上,您必须为每个选项设置一个值。例如:&lt;option value="1"&gt;Comp Time Used&lt;/option&gt;。这样,您将能够使用 request('category_id') 检索正确的 category_id。

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多