php 在 Laravel 集合对象中添加新元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33828769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add new element in laravel collection object
提问by Talib Hussain
I want to add new element in $items array, I don't want to use joins for certain reasons.
我想在 $items 数组中添加新元素,出于某些原因我不想使用连接。
$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.' ;'));
foreach($items as $item){
$product = DB::select(DB::raw(' select * from product
where product_id = '. $id.';' ));
$item->push($product);
}
what should i do, please help, thnx in advance
我该怎么办,请帮忙,提前谢谢
回答by Pastor Bones
It looks like you have everything correct according to Laravel docs, but you have a typo
根据 Laravel 文档,您似乎一切都正确,但是您有一个错字
$item->push($product);
Should be
应该
$items->push($product);
I also want to think the actual method you're looking for is put
我也想认为你正在寻找的实际方法是 put
$items->put('products', $product);
回答by Alpy
As mentioned above if you wish to as a new element your queried collection you can use:
如上所述,如果您希望将查询的集合作为新元素,您可以使用:
$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.' ;'));
foreach($items as $item){
$product = DB::select(DB::raw(' select * from product
where product_id = '. $id.';' ));
$items->push($product);
// or
// $items->put('products', $product);
}
but if you wish to add new element to each queried element you need to do like:
但是如果您希望向每个查询的元素添加新元素,您需要执行以下操作:
$items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.' ;'));
foreach($items as $item){
$product = DB::select(DB::raw(' select * from product
where product_id = '. $id.';' ));
$item->add_whatever_element_you_want = $product;
}
add_whatever_element_you_want
can be whatever you wish that your element is named (like product for example).
add_whatever_element_you_want
可以是您希望元素命名的任何内容(例如产品)。