MariachiLoco
MariachiLoco

Reputation: 33

Eloquent model updating more rows that it should laravel php

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.

Upvotes: 2

Views: 89

Answers (2)

Sagar Sheregar
Sagar Sheregar

Reputation: 75

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']);

Upvotes: 2

silver
silver

Reputation: 5311

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'] 
    );

Upvotes: 2

Related Questions