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

Bla*_*tus 1 php laravel-5

我想获取数据表单数据库表并在另一个表中创建一个新行。其中 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();
    }
Run Code Online (Sandbox Code Playgroud)

但是,这输出错误。

   Call to a member function save() on array
Run Code Online (Sandbox Code Playgroud)

请帮我。谢谢。

Wai*_*rim 6

如果您希望将记录从一个表复制到另一个表或只是复制同一个表中的记录,您可以简单地使用该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);
Run Code Online (Sandbox Code Playgroud)

注意:如果您只是在同一个表上复制Staff,请User在此示例中替换为。


Mar*_*lln 5

您正在尝试save在数组上运行该方法,但您想要的是在数组索引上使用它。

将您更改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();
}
Run Code Online (Sandbox Code Playgroud)

您可以使用forceCreate.

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