简体   繁体   English

将变量查询生成器插入 laravel 数据库

[英]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?我有查询生成器来显示“总计”这是代码,如何通过 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谢谢,我的输入 db在此处输入图像描述,错误总数在此处输入图像描述

If you just want ids to be present in query result, add it in your select.如果您只想在查询结果中显示 id,请将其添加到您的 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.另外我建议使用 eloquent 模型,查询纯数据,然后在 PHP 中计算并在计算后更新您的实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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