Hello,
I'm fetching a specific record with a DB table using MyTable::where(['type' => $sometype])->first(); Getting it successfully, updating some fields and saving with save(). Surprisingly, this record is updated along with another record that also has 'type' = $sometype. How on the earth is that possible (at the very least, I find this extremely confusing) and what can be done to prevent this? NOTE: originally the table did not have the autoincrement id field, but I have read somewhere that it may make problems in Laravel so I did add it, which did not solve the problem.
Best Regards
Model:
class MonthlyUpdateStatus extends Model
{
protected $table = 'monthly_update_status';
protected $primaryKey = 'date';
protected $guarded = [];
}
DB Table:
+------------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+----------------+
| date | varchar(255) | NO | | NULL | |
| step | int(11) | NO | | NULL | |
| created_at | timestamp | YES | | NULL | |
| updated_at | timestamp | YES | | NULL | |
| type | int(11) | NO | | NULL | |
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
+------------------+------------------+------+-----+---------+----------------+
Code:
$updateStatus = MonthlyUpdateStatus::where(['date' => $dateNow, 'type' => 1])->first();
$updateStatus->step = $nextStep;
$updateStatus->save();
Result: If I have in the table more than one record for this date (e.g. with type=1 and type=2), all will be updated with step=$nextStep.
Your table shows id
is the PK, your model has date
as the PK. They should be the same.
Yes, that was the problem. I had made the id to be the PK in the Model and it has started working correctly. Many thanks for the help!!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community