在 Laravel 集合对象中添加新元素


add new element in laravel collection object

我想$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);
        }

我该怎么办?

根据Laravel文档,看起来您一切都正确,但是您有一个错字

$item->push($product);

应该是

$items->push($product);

push方法将项追加到集合的末尾:

我还想认为您正在寻找的实际方法是put

$items->put('products', $product);

put方法设置集合中的给定键和值

如上所述,

如果您希望将查询的集合添加为新元素,您可以使用:

    $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);
    }

但是,如果您希望向每个查询的元素添加新元素,则需要执行以下操作:

    $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可以是您希望元素命名的任何名称(例如产品(。

如果要将项目添加到集合的开头,可以使用 prepend:

$item->prepend($product, 'key');
如果要

将产品添加到数组中,可以使用:

$item['product'] = $product;

如果您使用为 2 个表调用的数组,我已经解决了这个问题。例子你有, $tableA['yellow']$tableA['blue'] .您正在获得这两个值,并且希望在其中添加另一个元素以按其type分隔它们。

foreach ($tableA['yellow'] as $value) {
    $value->type = 'YELLOW';  //you are adding new element named 'type'
}
foreach ($tableA['blue'] as $value) {
    $value->type = 'BLUE';  //you are adding new element named 'type'
}

因此,两个表值都将具有名为 type 的新元素。

这就是我要做的...

$items = Item::find($id);
foreach($items as $item){
    $product = Product::find($id);
    $item->product = $product;
}

这将为每个$item分配$product

$item = collect();
$item->push($product);