首页 > 解决方案 > 如何从选定的连接表中添加新字段和值

问题描述

我有一个像这样的连接表

在此处输入图像描述

我想创建名为的新字段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);

标签: sqllaravelvue.js

解决方案


您需要使用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);

推荐阅读