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

我该怎么办?

看起来你的一切都是正确的according to Laravel docs,但是你有一个错字

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

如果您使用为 2 个表调用的数组,我已经解决了这个问题。你有的例子, $tableA['yellow']$tableA['blue'] 。您正在获取这 2 个值,并且您想在其中添加另一个元素以通过 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 的新元素。

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

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

如果您想将产品添加到数组中,您可以使用:

$item['product'] = $product;