Home > Back-end >  Laravel update specific column in database 'cost' and add supplier_id to another database
Laravel update specific column in database 'cost' and add supplier_id to another database

Time:04-20

i'm working with sensitive data hope you can help find if there any wrong in code's writing

i have list of suppliers in my database i added column 'cost' i'm trying to update and insert cost for existing suppliers from specific query and i created model and migration to get foreign keys too by adding the puled supplier id from the query

....
$suppliers_data = $suppliers_query->fetchall(PDO::FETCH_ASSOC); 
foreach ($suppliers_data as $supplier_data) {
    $supplier_name = $supplier_data['supplier_name'];
    $cost_rate = $supplier_data['Cost'];
    if (!Supplier::where('supplier', $supplier_name)->exists()) {
        Supplier::insert([
            'supplier' => $supplier_name,
            'cost_rate' => $cost_rate
        ]);
    } else {
        Supplier::update([
            'cost_rate' => $cost_rate // does this will update cost for the current supplier ?
        ]); 
    }
    $supplier_id = Supplier::where('supplier', $supplier_name)->pluck('supplier_id');
    Test::insert($supplier_id);
}
$supplier_count = test::count();
Test::update(['test_data_count' => $supplier_count]);

CodePudding user response:

Updating table data with supplier name is not correct here I believe. Instead of using supplier name in where condition using particular supplier id is recommended for better application. Names can be duplicate so its not a good idea to use supplier name in where.

In your current code I have 2 things to say :

You need to add where in update eloquent to work properly

Supplier::where('supplier', $supplier_name)
          ->update([
        'cost_rate' => $cost_rate // this will update cost for the current supplier
    ]);

Or to minimalize the code you can use updateorCreate method instead of making insert and update in the if() else() condition

Supplier::updateOrCreate(
    ['supplier' => $supplier_name],
    ['cost_rate' => $cost_rate]
);
  • Related