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

s2j5cfk0  于 2023-04-07  发布在  其他
关注(0)|答案(7)|浏览(263)

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

我该怎么办?

bmvo0sr5

bmvo0sr51#

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

$item->push($product);

应该是

$items->push($product);

push方法将一个项追加到集合的末尾:
我还希望您要查找的实际方法是put

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

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

eblbsuwk

eblbsuwk2#

如上所述,如果您希望将查询到的集合添加为新元素,您可以用途:

$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可以是你希望元素命名的任何东西(比如product)。

ftf50wuq

ftf50wuq3#

如果你想把item添加到集合的开头,你可以使用prepend:

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

gv8xihay4#

如果要将产品添加到阵列中,可以用途:

$item['product'] = $product;
hmae6n7t

hmae6n7t5#

我已经解决了这个问题,如果你使用数组调用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的新元素。

0g0grzrc

0g0grzrc6#

这是我会做的。。

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

这将为每个$item分配$product

u5i3ibmn

u5i3ibmn7#

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

相关问题