2017-01-02 113 views
0

我在foreach中遇到了语法错误。什么是使用内部查询生成器的阵列的foreach的正确方法,代码如下:发生如何在Laravel的查询生成器数组中使用foreach

public function postItems(Request $request, $id){ 
    $itemid = \DB::table('items_tables')->where('category_id','=',$id)->get();  

    DB::table('store_items')->insert(
    array('user_id' => \Auth::user()->id, 

     foreach($itemid as $itemids){ 
      'items' => $itemids->name, 
     } 

      'store_id' => $id) 
    ); 

    return view('actions.itemstore'); 
} 

语法错误中的foreach如下:

Parse error: syntax error, unexpected 'foreach' (T_FOREACH), expecting ')'

$ itemids->名称变量有许多值。我需要循环这一点。

+0

认真吗?你没有得到错误?你见过像你写的foreach($ itemid as $ itemids)吗?{ 'items'=> $ itemids-> name, } – rahulsm

+0

我做了一些修改。请检查一下。 –

+2

@JaseelBavu你的代码有太多错误。你正试图用'insert()'结构错误的数组。你正在使用loop而不是'pluck()'。数据库架构不好。错误的语法无处不在。你应该真的阅读Laravel和PHP文档。这会为你节省很多时间。 –

回答

0

这HOULD是这个样子:

public function postItems(Request $request, $id){ 
    $itemid = \DB::table('items_tables')->where('category_id','=',$id)->get(); 
    foreach($itemid as $itemids) { 
     $data_to_insert = [ 
      'user_id' => \Auth::user()->id, 
      'store_id' => $id, 
      'items' => $itemids 
     ]; 
     DB::table('store_items')->insert($data_to_insert); 
    } 

    return view('actions.itemstore'); 
} 
0

如果你想要去的全Laravel,您可以使用集合写:

public function postItems(Request $request, $id) 
{ 
    collect(\DB::table('items_tables')->where('category_id','=',$id)->get())->each(function ($item) use ($id) { 
     \DB::table('store_items')->insert([ 
      'user_id' => \Auth::user()->id, 
      'store_id' => $id, 
      'item_name' => $item->name 
     ]); 
    }); 

    return view('actions.itemstore'); 
} 

如果使用Laravel 5.3,你可能放弃collect()也是如此,因为我们现在即使在使用数据库时也能获得集合。

+0

仍显示相同的错误 –

+0

它显示此行的错误 foreach($ itemid as $ itemids){ –

+0

使用Laravel集合重写了它。我不确定你的专栏的名字,但你必须知道他们,对吧? –

相关问题