簡體   English   中英

將變量查詢生成器插入 laravel 數據庫

[英]insert variable query builder into laravel database

我有查詢生成器來顯示“總計”這是代碼,如何通過 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
            ]);
         }

謝謝,我的輸入 db在此處輸入圖像描述,錯誤總數在此處輸入圖像描述

如果您只想在查詢結果中顯示 id,請將其添加到您的 select 中。

select(DB::raw('(a.price * b.weight) as total, a.id as a_id, b.id as b_id'))

然后遍歷您的數組結果,並根據您的需要進行特定的查詢。

如果您只想使用查詢結果更新數據庫而不使用它,您可以考慮使用更新查詢而不是僅從數據庫中選擇它。

另外我建議使用 eloquent 模型,查詢純數據,然后在 PHP 中計算並在計算后更新您的實體。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM