php - 将变量查询生成器插入 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
]);
}
解决方案
如果您只想在查询结果中显示 id,请将其添加到您的选择中。
select(DB::raw('(a.price * b.weight) as total, a.id as a_id, b.id as b_id'))
然后遍历您的数组结果,并根据您的需要进行特定的查询。
如果您只想使用查询结果更新数据库而不使用它,您可以考虑使用更新查询而不是仅从数据库中选择它。
此外,我建议使用 eloquent 模型,查询纯数据,然后在 PHP 中计算并在计算后更新您的实体。
推荐阅读
- django - Django 和 Certbot - 未经授权的无效响应 (HTTPS)
- javascript - 在 ReactJS 项目中单独服务 NodeJS 服务器
- sql - SQL - 使用由管道分隔的键加入
- file - ADF-Azure 数据工厂多通配符过滤
- c++ - 调用多个 lambda 并返回聚合结果
- react-native - 解析 JSON 以在 React Native 中建模变得未定义
- java - Kubernetes 上的 Spark 作业失败,没有特定错误
- kubernetes - Kubernetes:相同的节点但不同的 IP
- c# - 时间:2019-01-10 标签:c#loadingimagesfromdatatabletopicturebox
- javascript - 包含在 html 中的 Javascript 命名捕获组正则表达式问题