需要一个查询,允许我使用B列中的值添加A列中的值

时间:2018-06-06 11:14:48

标签: php mysql laravel

需要一个查询,允许我添加列A的新数据和列B上的最后一个数据,然后存储在同一个表中。

为了澄清,在表格中我有名为quantity_added和quantity_left的列。

存储新数据时,我想为列quantity_added添加新值,并将列quantity_left上的最后一个值添加为剩余的列数量的新值,作为新数据的存储。

E.g

Quantity_added = 2, quantity_left = 10,

quantity_left = Quantity_added + quantity_left

2 + 10 = 12

的新值
quantity_left = 12

表格示例

      id  description    quantity_added      quantity_left     created  

      1    shoes             2                   10           21-4-2018  

      2    shoes             34                  44           22-4-2018

      3    shoes             6                   50           23-4-2018

提前致谢

5 个答案:

答案 0 :(得分:0)

尝试类似的

$data = ['Quantity_added' => 2]; // your initial data   
$data['quantity_left'] = $data['Quantity_added']; // assign Quantity_added value to quantity_left 
$model = EloquentModel::orderByDesc('primary_key')->first(['quantity_left']) 

if ($model) {
    // if has record ind db add last record quantity_left value in $data['quantity_left'] 
    $data['quantity_left'] = $model->quantity_left;
}

Model::create($data);

答案 1 :(得分:0)

在我的回复中,我认为该表是一个id列,如下所示:

TABLE_NAME

  • 标识,

  • Quantity_added,

  • Quantity_left

    $ add_quantity = DB :: table('Table_name') - > select('Quantity_added') - > where('id','=',$ id) - > first(); $ add_quantity = $ add_quantity-> Quantity_added; DB :: table('Table_name') - > increment('quantity_left',$ add_quantity,['id'=> $ id]);

每当我必须在Laravel中进行SQL查询时,我都会查阅文档的这一页https://laravel.com/docs/5.5/queries

答案 2 :(得分:0)

     public function update(){ 
     $table=new Table;
     $last_quantity_added=Table::select('quantity_added')->orderBy('quantity_added', 'desc')->first();
     $table->quantity_added=$last_quantity_added+$quantity_added_value;
     $table->quantity_left=$quantity_added_value;
     $table->description=$desc_value;
     $table->created=$current_date;
     $table->save();
    }

答案 3 :(得分:0)

感谢大家的贡献。为实现上述目标,以下是适用于我的代码

 //select the last value of quantity_left
    $old_quantity = Asset::latest()->first()->quantity_left;
    $new_quantity = $request->quantity_added;

 //add it up with the new quantity_added value
    $asset->quantity_left = collect([ $old_quantity,  $new_quantity ])->sum();

如需更多阅读,请查看https://laravel.com/docs/5.6/collections#method-sum

答案 4 :(得分:-1)

UPDATE `table` 
SET 
    `quantity_added` = NEW_VALUE, 
    `quantity_left` = `quantity_left` + NEW_VALUE