简体   繁体   中英

Update table value when inserting to other table

I'm working on Laravel and my question is: How can I update value in one table when inserting data to another? Do I have to write new function in controller or update existing or maybe its done on form level in eloquent (view?)?

For example:

That's my OrderController.php function handling inserting:

public function insert(Request $request){

        $order = new order;

        $order->material_id = $request->material_id;
        $order->invoice_id = $request->invoice_id;
        $order->count_order = $request->count_order;

        $order->save();
        return redirect('/order');
    }

order.blade.php form that inserts data looks like:

<form method="POST" action="/order">

    <div class="form-group">

        <input list="invoices" name="invoice_id" autocomplete="off">
        <datalist id="invoices">
        @foreach($invoices as $invoice)
        <option value="{{$invoice->id}}">{{$invoice->number}}</option>
        @endforeach
        </datalist>

        <input list="materials" name="material_id" autocomplete="off">
        <datalist id="materials">
        @foreach($materials as $material)
        <option value="{{$material->id}}">{{$material->name}}</option>
        @endforeach
        </datalist>

        <input type="count" name="count_order" placeholder="Ilość zamówiona" autocomplete="off">

    </div>


    <div class="form-group">
        <button type="submit" class="btn btn-primary">Dodaj zamówienie</button>
    </div>
{{ csrf_field() }}
</form>

Orders table has:

| id | count_order | material_id | invoice_id |

Materials table has:

| id | name | count_all | count_current | price_unit |

Now I want to update column (add value) count_all in Materials when I post value in a form when inserting to count_order column in Orders table.

you can use if

$query = $order->save();

if($query){
  //do update data
}

您可以在Order模型中扩展save()函数,在那里您将拥有所需的值,并且可以在Materials中执行更新

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM