0
votes

I have two tables, one is items table which has the description of the item like (category, name, price ..etc).

And that table has a relation one-to-one with another table called prices table, which represent the price of each item. So each item has one price.

Now I have a form for adding items (one or multiple rows):

  • item_id(int), name(text), price(number).
  • item_id(int), name(text), price(number).
  • item_id(int), name(text), price(number).

I want to insert those items directly to database using eloquent relationship tool, here's what I did:

foreach ($request as $key => $value) {
    $item  = [];
    $price = [];
    $item['item_id'] = $value['item_id'];
    $item['name']    = $value['name'][$i];
    $price['price']  = $value['price'][$i];
    Item::create($item);
    Price::create($price);
}

Is there's a better way to insert the request directly to both tables using eloquent, without creating arrays?

1

1 Answers

0
votes

You can use createMany method for that. See Docs

$items = $request->get('items');
Item::createMany($items);

$prices = $request->get('prices');
Price::createMany($prices);