Php 有没有办法在DB::raw中插入值?拉维尔

Php 有没有办法在DB::raw中插入值?拉维尔,php,html,mysql,laravel,Php,Html,Mysql,Laravel,我有一个products表,它有一个名为quantity的列。我还有一个名为member_product的透视表,它也有一个quantity列 我希望能够从products表中减去quantity,并从member_product表中减去quantity 类似于使用成员产品作为购物车更新库存数量。我似乎不明白 Tables products id | name | quantity member_product product_id | member_id | quantity

我有一个products表,它有一个名为quantity的列。我还有一个名为member_product的透视表,它也有一个quantity列

我希望能够从products表中减去quantity,并从member_product表中减去quantity

类似于使用成员产品作为购物车更新库存数量。我似乎不明白

Tables  
products  
id | name | quantity  

member_product  
product_id | member_id | quantity
看法

<table>
<thead>
    <tr>
        <th>Name</th>
        <th>Qty</th>
    </tr>
</thead>
@foreach($members->products as $p)
<tbody>
    <tr>
        <td><input type="hidden" name="productid[]" value="{{$p->id}}">{{$p->name}}</td>
        <td><input type="hidden" name="qty[]" value="{{$p->pivot->qty}}">{{$p->pivot->qty}}</td>
    </tr>
</tbody>
@endforeach
</table>  
使用当前代码,我获得了所需的ID,还可以运行
db::raw('qty-1')

是否可以在
db::raw
中插入一个值,以便使用my Where指定的ID数量,该ID来自my product_成员表。还是我走错了路


我很难处理数组,所以请耐心等待。

是的,这是可能的。试着这样做

public function updateProduct()
{

$productid = $request['productid'];
$qty     = $request['qty'];

products = DB::table('products')
      ->join('member_product','member_product.product_id','=','products.id')
      ->whereIn('products.id', $productid)
      ->update(['products.quantity' => DB::raw("products.quantity - member_product.quantity")]);
}  

您需要在字段名之前使用表名,以避免查询中出现不明确的列名。

更好的方法是在成员上定义一个belongTomany,然后按如下方式更新

Member::find(1)->products()->updateExistingPivot($productId, [
    'qty' => 1
]);

当然,您还需要更新产品数量。

->update(['qty'=>DB::raw('qty-'(int)$qty)]@marveln我试过了,但它只从数量中扣除了1,而不是从我的$qty中扣除了3。这不是精确的解决方案。这只是建议您如何在一次查询更新中从两个不同的表中减去两个不同的值。在哪一行出现了错误?谢谢你的工作!!它按照我的要求工作。我必须将->其中('product.id,$productid)更改为->其中('id',$productid),因为它无法定位product.id。尽管如此,我还是接受了你的回答,再次感谢你。是的,我把表名弄错了。它应该是产品而不是产品。很高兴我能帮助你。我知道我会在将来的项目中记住这个方法。我对拉威尔还是新手,所以我现在必须坚持我所知道的。谢谢你的建议。
Member::find(1)->products()->updateExistingPivot($productId, [
    'qty' => 1
]);