Php 如何在Laravel中使用查询生成器的foreach内部数组
我在foreach中发现语法错误。在查询生成器的数组中使用foreach的正确方法是什么,代码如下:Php 如何在Laravel中使用查询生成器的foreach内部数组,php,arrays,laravel,foreach,syntax,Php,Arrays,Laravel,Foreach,Syntax,我在foreach中发现语法错误。在查询生成器的数组中使用foreach的正确方法是什么,代码如下: public function postItems(Request $request, $id){ $itemid = \DB::table('items_tables')->where('category_id','=',$id)->get(); DB::table('store_items')->insert( array('user
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中出现如下语法错误:
分析错误:语法错误,意外的'foreach'(T_foreach),应为''
$itemids->name变量有许多值。我需要循环浏览这个。这个应该是这样的:
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');
}
如果您想使用完整的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(),因为现在我们甚至在使用DB时也会得到集合。真的吗?你不会出错吧?你见过像你写的foreach($itemid作为$itemids){'items'=>$itemids->name,}这样的东西吗?我做了一些更改。请检查。@JaseelBavu您的代码有太多错误。您试图对结构错误的数组使用
insert()
。您使用的是循环,而不是pluck()
。数据库架构不好。到处都是错误的语法。您应该真正阅读Laravel和PHP文档。这将为您节省大量时间。仍然与我提出的列重复仍然显示相同的错误这一行显示错误foreach($itemid as$itemids){使用Laravel集合重写它。我不确定您列的名称,但您必须知道它们,对吗?