sql - 如何从选定的连接表中添加新字段和值
问题描述
我有一个像这样的连接表
我想创建名为的新字段qty_exceed
,该值基于
( qty_stock
- qty_taken
)
我必须在查询中执行此操作还是进行单独操作并将其存储在变量中?
我的代码
$getmaterial = ContractProduct::select(
'product_item.ref_rof_id',
'product_item.code',
'product_item.qty_stock',
'contract_product.qty_taken'
)
->where('ref_rof_id', $getrof->ref_rof_id)
->join('product_item', 'contract_product.ref_product_id', '=', 'product_item.code')
->get();
$data['getquoid'] = $getquoid;
$data['getmaterial'] = $getmaterial;
$view = $this->module_path . '.next-create';
return response()->view($view, $data);
解决方案
您需要使用DB::raw
但请记住,原始语句将作为字符串注入到查询中,因此您应该非常小心,不要造成 SQL 注入漏洞。
使用DB::raw
您的代码将如下所示:
$getmaterial = ContractProduct::select(
'product_item.ref_rof_id',
'product_item.code',
'product_item.qty_stock',
'contract_product.qty_taken',
ContractProduct::raw('product_item.qty_stock - contract_product.qty_taken as qty_exceed')
)
->where('ref_rof_id', $getrof->ref_rof_id)
->join('product_item', 'contract_product.ref_product_id', '=', 'product_item.code')
->get();
$data['getquoid'] = $getquoid;
$data['getmaterial'] = $getmaterial;
$view = $this->module_path . '.next-create';
return response()->view($view, $data);
推荐阅读
- macos - macOS 代码签名并公证 .app 和 .dmg 以进行分发
- nginx - /etc/nginx/sites-enabled/default 错误中 0.0.0.0:80 的重复默认服务器在哪里重复?
- c++ - 用于解析 win64 堆栈跟踪的命令行客户端(可以访问符号服务器)
- amazon-web-services - 我可以在 AWS IAM 上注册具有多个证书的 IDP
- java - 将项目从 Eclipse 移动到 Intellij,现在我收到错误
- java - 银行银行发生异常 = new Bank(bankNaam);
- django - 无法在 Django 2.2 中呈现静态文件
- azure - Azure 托管数据磁盘无法使用 ansible parted 进行分区
- node.js - 如何为 Winston 记录仪着色?
- c# - 在 ASP.NET Core 2.2 中使用异步缩小 js