在 laravel 中更新循环的表数组

问题描述 投票:0回答:1

我有一个表,我想更新它,但每次更新时总是出现问题,它说它为空或请求列未找到0,有人可以帮助我吗?有什么想法吗?

更新控制器

 public function update(Request $request, string $id)
    {
        

          $invoice = Invoice::find($id);
          $input = $request->all();
          $invoice->update($input);

        $title = $request->title;
        $quantity = $request->quantity;
        $unit_price = $request->unit_price;
        $sort_order = $request->sort_order;

            $invoiceDetails = [];

            for ($i = 0; $i < count($title); $i++) {
                $invoiceDetails[] = [
                    'sort_order' => $sort_order[$i],
                    'title' => $title[$i],
                    'quantity' => $quantity[$i],
                    'unit_price' => $unit_price[$i],
                ];
            }

             

            $invoice = $invoice->invoice_detail()->update($invoiceDetails);

        return redirect('invoice')->with('flash_message', 'Updated');

    }

发票模型

class Invoice extends Model
{
    use HasFactory;
    protected $table = 'invoices';
    protected $primaryKey = 'id';
    protected $fillable = ['user', 'company', 'invoice_month'];
    
    const UPDATED_AT = 'modified';
    const CREATED_AT = 'created';
    
    public function invoice_detail(){
        return $this->hasMany(Invoice_detail::class, 'invoice_id');

    }

}

发票明细模型

class Invoice_detail extends Model
{
    use HasFactory;
    protected $table = 'invoice_details';
    protected $primaryKey = 'id';
    protected $fillable = ['title', 'quantity', 'unit_price', 'invoice_id'];

    const UPDATED_AT = 'modified';
    const CREATED_AT = 'created';
    public function invoice(){
        return $this->belongsTo(Invoice::class);
    }

}

路线


Route::get('invoice', [InvoiceController::class, 'index']);

Route::get('search', [InvoiceController::class, 'search']);

Route::resource('/invoic', InvoiceController::class);

我只想在 Laravel 中更新正确的代码,它在一个数组中,因为我的视图是一个引导表

php laravel sqlite
1个回答
0
投票

您正在传递一个多维数组,因此您的键是嵌套的,因此被视为丢失。

将代码更改为:

    for ($i = 0; $i < count($title); $i++) {
        $invoiceDetails = [
            'sort_order' => $sort_order[$i],
            'title' => $title[$i],
            'quantity' => $quantity[$i],
            'unit_price' => $unit_price[$i],
        ];

        $invoice = $invoice->invoice_detail()->update($invoiceDetails);
    }

         

我根据您的代码假设您用于为键赋值的变量始终存在。

也许您还应该考虑对您的请求字段进行一些验证。

© www.soinside.com 2019 - 2024. All rights reserved.