简体   繁体   English

从数组Laravel中的db插入数据

[英]insert data from db in array Laravel

//controller function
public function storeBaritems()
{
    $id = Auth::user()->id;
    $bartypearray = array();
    $bartypes = request('select1');     // <select id="select1" name="select1[]"
    $r = 0;
    foreach ($bartypes as $type) {
        $bartypearray[$r] = Bartype::select('bartype_id')
                            ->where('bar_type_name','like',$type)
                            ->where('restaurant_id','like',$id)
                            ->get();
        $r += 1;
    }
    $baritems = request('itemname');   //<input type="text" class="hookah-field" name="itemname[]">
    $descriptions = request('description');  //<input type="text" class="hookah-field" name="description[]">
    $quantity = request('quantity'); //<input type="text" class="hookah-field" name="quantity[]">
    $prices = request('price');  //<input type="text" class="hookah-field" name="price[]">
    $i = 0;
    foreach ($baritems as $item) {
            Bar_menu::create([
                'item_name'=>$item,      
                'description'=>$descriptions[$i], 
                'quantity'=>$quantity[$i],
                'price'=>$prices[$i],
                'res_id'=>$id,
                'type_id'=>$bartypearray[$i]
                ]);
            $i += 1;
    }
} 

The HTML is dynamic form and it generates new input fields with same "name" attribute. HTML是动态形式,它会生成具有相同“名称”属性的新输入字段。 After calling the function from route, I am getting this error as in screenshot error screenshot 从路由调用函数后,出现此错误,如屏幕截图错误屏幕截图所示

I think problem is with inserting the data in bartypearray[] . 我认为问题在于在bartypearray[]插入数据。 Any solution? 有什么办法吗?

In your first foreach loop, when you try to populate $bartypearray with data, you are actually populating it with an object array. 在第一个foreach循环中,当您尝试用数据填充$ bartypearray时,实际上是在用对象数组填充它。 That's why you get a '[]' as an input instead of an integer. 这就是为什么您将“ []”作为输入而不是整数的原因。

What I suggest you do, is to access the bartypeid in the second foreach loop like this: 'type_id'=$bartypearray[$i] -> bartypeid; 我建议您做的是在第二个foreach循环中访问bartypeid,如下所示:'type_id'= $ bartypearray [$ i]-> bartypeid;

I think it should work.. 我认为应该可以。

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

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