0

In my web app I am trying to update one of many notes that are on one work order.

If I write query like this (Case 1):

// NOTE UPDATE WORKING FINE
Model::where('RN_key', $RN_key)->where('anNo', $anNo)->update(['acNote' => $request['note']]);

I get what I want, it's working fine - only one note on work order is updated as it should be.

If I write query update using first() and save() functions like this (Case 2):

// NOTE UPDATE NOT WORKING - Updates EVERY note on one work order but should update ONLY one
$getWorkSpecification = __vVX_ServisniNalog_Radovi::where('RN_key', $RN_key)->where('anNo', $anNo)->first();
$getWorkSpecification->acNote = $request['note'];
$getWorkSpecification->save();

Then it updates and overwrites every note on that same order thus every other note on order is lost. Why is that happening? I need to make it work with first() and save() functions because then it fires event so Laravel Auditing can save audit so I can have logs on every model change any user make.

With Case 1, every note updates fine but no audits are logged and thats the problem.

Dino Numić
  • 1,414
  • 2
  • 9
  • 17
Dome
  • 11
  • 4
  • can you try `->get()->first()` ? – Taha Paksu Aug 28 '19 at 10:38
  • What is the **primary key** in your Model ? When you use `save()` on an instance, it uses the primary key to target only one entry. – N69S Aug 28 '19 at 10:40
  • @TahaPaksu yes, just tried it, the result is same, it updates every note on one order, no difference :/ – Dome Aug 28 '19 at 10:43
  • @N69S my model is actually a view created in SQL Server, In model I wrote: public $primaryKey = 'RN_key'; so laravel know primary key, but I am not sure if that's how it works? – Dome Aug 28 '19 at 10:46
  • Your primary key probably isn't a primary key at all. Try replacing `first()` with `count()`. If it's more than 1, then RN_key is not a primary key. – IGP Aug 28 '19 at 15:18
  • Yes you are right, I have multiple rows with same RN_key - if order has 3 notes, then I have 3 rows with same RN_key in my SQL view, and I get one note using RN_key and note number (2 where clause). Can I still make it work somehow? I really need this. Thanks for reply! – Dome Aug 28 '19 at 21:14

0 Answers0