php - 使用 Laravel 5 动态添加表单输入字段和存储值

标签 php mysql html laravel laravel-5.4

我正在使用产品和价格模型。我的产品表有一个 id 和名称列,而我的价格表有一个 id、product_id、cost 和 date 列。价格表中的 product_id 引用了产品表中的 id。我的表单为每个产品显示一个字段,以便用户不时输入价格。我的挑战是如何处理请求数据,以便价格与 product_id 相对应。以下是我到目前为止编写的代码

表格

<form class="form-horizontal" method="POST" action="{{ url('/home/prices') }}">
{{ csrf_field() }}
@if(isset($products) && !empty($products))
    @foreach($products as $product)
        <div class="form-group">
            <div>
                <input type="hidden" class="form-control" name="product_id[]" value="{{ $product->id }}">
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2" for="{{ $product->name }}">{{ ucwords($product->name) }}</label>

            <div class="col-sm-3">
                <input type="text" class="form-control" name="cost[]">
            </div>
        </div>
    @endforeach
@else
    Sorry, no product available currently.
@endif

<button type="submit" class="btn btn-default">Add</button>
</form>

价格 Controller

public function store(Request $request)
{
//dd($request);
foreach ($request->input('cost') as $cost) {
    Price::create([
        'product_id' => $request->product_id,
        'date' => Carbon::now(),
        'cost' => $cost,
        'trend' => 0
    ]);
}

return redirect('/home');
}

这是我转储请求数据时得到的 enter image description here

当然我的代码会抛出这个错误 在 Builder->insertGetId(array('product_id' => array('1', '2', '3'), 'date' => object(Carbon), 'cost' => '14.05', 'trend' => 0, 'updated_at' => '2017-08-07 11:21:47', 'created_at' => '2017-08-07 11:21:47'), 'id')

我该如何解决这个问题?

最佳答案

foreach ($request->input('cost') as $key=>$cost) {

    Price::create([
        'product_id' => $request->product_id[$key],
        'date' => Carbon::now(),
        'cost' => $cost,
        'trend' => 0
    ]);
}

如您所见,整个数组都在产品 ID 中传递,因此您需要提及需要插入的特定 ID

关于php - 使用 Laravel 5 动态添加表单输入字段和存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45545794/

相关文章:

html - 在 div 中垂直对齐具有响应字体大小的文本 div

PHP SQL - 按国家排序

PHP - 作为助手的特征

mysql - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException : Unknown column 'poi' in 'where clause'

PHP MySQL 日期大于

javascript - 是否可以使用 Javascript 或任何其他方式在 HTML 或 CSS 元素中使用本地镜像?

php - MySQL 和 PHP : Using SELECT FOR UPDATE

php - 导出数据库中所有表的某些列

PHP 无法识别 Mysql 值

php - PHP MYSQL 如何添加多个评分结果