简体   繁体   English

Laravel,将行复制到另一个具有雄辩关系的表

[英]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.其中 1 个 PO 有多个 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.您正在尝试在数组上运行save方法,但您想要的是在数组索引上使用它。

Change your foreach to this and it should work (assuming columns are the same).将您的foreach更改为此,它应该可以工作(假设列相同)。

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 .您可以使用forceCreate缩短此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.如果您希望将记录从一个表复制到另一个表或只是复制同一个表中的记录,您可以简单地使用repliacate()方法。

        $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.注意:如果您只是在同一张表上复制,请在此示例中将Staff替换为User

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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