2017-01-02 43 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集合重寫了它。我不確定你的專欄的名字,但你必須知道他們,對吧? –

相關問題