简体   繁体   中英

Laravel, copy row to another table with eloquent relationship

I want to get the data form database table and create a new row in another table. Which 1 PO have many PoProducts.

    $_getPO = Order::find($id);
    $_getPOProducts= OrderProducts::where('order_id', $id)->get();

    $order_no = $_getPO->order_no;
    $eta = $_getPO->eta;

    $_Order = new DeliveryOrders();
    $_Order->order_no = $order_no;
    $_Order->eta = $eta;
    $_Order->save();

    $POProduct = array();
    foreach($_getPOProducts as $i => $_getPOProduct)
    {
        $POProduct[] = new DeliveryOrderProducts();
        $POProduct[] = $_getPOProduct->order_id;
        $POProduct[] = $_getPOProduct->item_id;
        $POProduct[] = $_getPOProduct->qty;
        $POProduct->save();
    }

But, this output an error.

   Call to a member function save() on array

Please help me. Thanks.

You are trying to run the save method on the array but what you want is to use it on the array index instead.

Change your foreach to this and it should work (assuming columns are the same).

foreach($_getPOProducts as $i => $_getPOProduct)
{
    $POProduct[$i] = new DeliveryOrderProducts();
    $POProduct[$i]->order_id = $_getPOProduct->order_id;
    $POProduct[$i]->item_id = $_getPOProduct->item_id;
    $POProduct[$i]->qty = $_getPOProduct->qty;
    $POProduct[$i]->save();
}

You can shorten this by using forceCreate .

foreach($_getPOProducts as $i => $_getPOProduct)
{
    $POProduct[$i] = (new DeliveryOrderProducts())->forceCreate($_getPOProduct->only(['order_id', 'item_id', 'qty']));
}

If you wish to copy records from one table to another or just duplicate a record in the same table you could simply use the repliacate() method.

        $user = User::findOrFail($id);
        
        // replicate (duplicate) the data
        $staff = $user->replicate();

        // make into array for mass assign. 
        //make sure you activate $guarded in your Staff model
        $staff = $staff->toArray();

        Staff::firstOrCreate($staff);

Note: in case you're only duplicating on the same table replace Staff with User on this example.

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