skip to Main Content

I have a table without primary key that looks like this:

user_id config_key config_value
2296 config_key_1 config_value_1
2296 config_key_2 config_value_2
2296 config_key_3 config_value_3
2296 config_key_4 config_value_4

And every time I try to update one value from that table, for some reason the rest of the table is updated with the same values, like this:

user_id config_key config_value
2296 config_key_1 config_value_1
2296 config_key_2 config_value_1
2296 config_key_3 config_value_1
2296 config_key_4 config_value_1

My query looks like this:

$ConfigValue = AppUserConfig::where('user_id', 2296)
                ->where('config_key', 'config_key_1')
                ->first();
$ConfigValue->config_value = config_value_1;
$ConfigValue->save();

I just basically need to update one row of my table, from this:

user_id config_key config_value
2296 config_key_1 config_value_1
2296 config_key_2 config_value_2
2296 config_key_3 config_value_3
2296 config_key_4 config_value_4

To this:

user_id config_key config_value
2296 config_key_1 new_custom_value
2296 config_key_2 config_value_2
2296 config_key_3 config_value_3
2296 config_key_4 config_value_4

But not sure, what is happening 🙁

Both solutions pretty much solved it, thanks, everyone.

2

Answers


  1. There’s nothing weird going on, when you update a record using Eloquent, your update statement would use the primary key to identify that record, we can just assume that it tries to update all rows with id 2296. you can use debug tools like clockwork or telescope to verify the actual SQL statement queries when you run your code

    You can also try using Query builder for update statement
    e.i.

    DB::table('app_user_config_whatever')
        ->where('user_id', 2296)
        ->where('config_key', 'config_key_1')
        ->update(['config_value' => 'config_value_1']);
    

    but the best approach would be to create a proper relationship between user and config, like having the config belognsTo a user, then you can perform something like

    $user->config()
        ->where('config_key', 'config_key_1')
        ->update(['config_value' => 'config_value_1']);
    

    or

    $user->config()
        ->updateOrCreate( 
            ['config_key' => 'config_key_1' ], 
            ['config_key' => 'config_key_1', 'config_value' => 'config_value_1'] 
        );
    
    Login or Signup to reply.
  2. you can update by using update query like this

    $ConfigValue = AppUserConfig::where('user_id', 2296)
                    ->where('config_key', 'config_key_1')
                    ->update(['config_value'=>'config_value_1']);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search