简体   繁体   中英

insert variable query builder into laravel database

i have query builder to show 'total' here is the code, how to insert total to my inputs database by id? **

$total =DB::table('prices as a')
        ->join('inputs as b', function ($join){
            $join->on('a.category_id', '=','b.category_id');
        })
        ->select(DB::raw('(a.price*b.weight)as total'))
        ->get()
dd($total) is
    #items: array:3 [▼
        0 => {#1248 ▼
          +"total": 2000.0
        }
        1 => {#1252 ▼
          +"total": 600.0
        }
        2 => {#1247 ▼
          +"total": 200.0
        }
      ]
    }

**

DB::table('inputs')->insert([
            'total'=>$total,
        ]);
its my store controller 
foreach($category as $key => $no)
        {
            $$module_name_singular = $module_model::create([
                'category_id'=>$category[$key],
                'user_id'=> $user,
                // dd($category[$key]),    
                // 'total' =>$total[$key],
                // dd($total[$key]),
                // dd($user),
                'weight'=> $weight[$key],
                // dd($weight[$key]),

                // 'total' => 6,
                'created_by_name' => auth()->user()->name
            ]);
         }

thank you, my inputs db enter image description here and error total enter image description here

If you just want ids to be present in query result, add it in your select.

select(DB::raw('(a.price * b.weight) as total, a.id as a_id, b.id as b_id'))

Then iterate over your array result, and make queries specific for your needs.

If you just want to update database using your query result without using it, you can consider to use update query instead of just selecting this from the database.

Also I reccomend to use eloquent models, query plain data and then calculate it in PHP and update your entities after calculations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM