如何将foreach循环数据存储到另一个模型中?

时间:2017-07-15 09:16:35

标签: php

我想将foreach循环数据存储到另一个变量中。问题是我可以将数据存储到数据库中但是当我dd()输出时它只显示分配给模型的最后一个数据。

如何从新模型中获取数组数据?

foreach ($carts as $cart)
{
    $buy = new Buy();               
    $buy->product_id = $cart->product_id;
    $buy->user_id = $cart->user_id;
    $buy->price = $cart->price;
    $buy->extened = $cart->extened;
    $buy->installation = $cart->installation;
    $buy->support = $cart->support;             
    $buy->feature_image = $cart->feature_image;
    $buy->name = $cart->name;
    $buy->save();               
}

dd($buy);  // it returns only last inserted data ..

1 个答案:

答案 0 :(得分:2)

当然,您将获得最新的插入数据。使用以下代码获取所有插入的数据。这是因为最后执行foreach循环时,$buy会有最新的$cart信息。

您可以使用以下代码获取所有Buy模型。我们将创建一个空数组并将$buy添加到数组中。

$buys = array(); // I don't care about the name of the array lol.
foreach ($carts as $cart)
{
    $buy = new Buy();               
    $buy->product_id = $cart->product_id;
    $buy->user_id = $cart->user_id;
    $buy->price = $cart->price;
    $buy->extened = $cart->extened;
    $buy->installation = $cart->installation;
    $buy->support = $cart->support;             
    $buy->feature_image = $cart->feature_image;
    $buy->name = $cart->name;
    $buy->save();

    array_push($buys,$buy);        
}

它会将每个记录存储在$buys数组中,然后您就可以对该数组执行任何操作。

如果这是您想要的,请告诉我。如果您还有其他问题,请与我们联系。

更新:您可以在foreach上运行$buys循环来显示/更新/删除条目。