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
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 likeclockwork
ortelescope
to verify the actual SQL statement queries when you run your codeYou can also try using Query builder for update statement
e.i.
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 likeor
you can update by using update query like this