add new element in laravel collection object

前端 未结 3 1547
陌清茗
陌清茗 2020-12-15 02:47

I want to add new element in $items array, I don\'t want to use joins for certain reasons.

$items = DB::select(DB::raw(\'SELECT * FROM items WHE         


        
相关标签:
3条回答
  • 2020-12-15 02:54

    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).

    0 讨论(0)
  • I have solved this if you are using array called for 2 tables. Example you have, $tableA['yellow'] and $tableA['blue'] . You are getting these 2 values and you want to add another element inside them to separate them by their 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'
    }
    

    So, both of the tables value will have new element called type.

    0 讨论(0)
  • 2020-12-15 03:13

    It looks like you have everything correct according to Laravel docs, but you have a typo

    $item->push($product);
    

    Should be

    $items->push($product);
    

    I also want to think the actual method you're looking for is put

    $items->put('products', $product);
    
    0 讨论(0)
提交回复
热议问题