首页 > 解决方案 > 将变量查询生成器插入 laravel 数据库

问题描述

我有查询生成器来显示“总计”这是代码,如何通过 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
            ]);
         }

谢谢,我的输入 db在此处输入图像描述 ,错误总数在此处输入图像描述

标签: phpdatabaselaravel

解决方案


如果您只想在查询结果中显示 id,请将其添加到您的选择中。

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

然后遍历您的数组结果,并根据您的需要进行特定的查询。

如果您只想使用查询结果更新数据库而不使用它,您可以考虑使用更新查询而不是仅从数据库中选择它。

此外,我建议使用 eloquent 模型,查询纯数据,然后在 PHP 中计算并在计算后更新您的实体。


推荐阅读