![](/img/trans.png)
[英]Prevent to execute insert statements to database on laravel query builder
[英]insert variable query builder into laravel database
我有查询生成器来显示“总计”这是代码,如何通过 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
]);
}
如果您只想在查询结果中显示 id,请将其添加到您的 select 中。
select(DB::raw('(a.price * b.weight) as total, a.id as a_id, b.id as b_id'))
然后遍历您的数组结果,并根据您的需要进行特定的查询。
如果您只想使用查询结果更新数据库而不使用它,您可以考虑使用更新查询而不是仅从数据库中选择它。
另外我建议使用 eloquent 模型,查询纯数据,然后在 PHP 中计算并在计算后更新您的实体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.