say Table A and Table B (table B has a foreign key a_id)
I want to be able to update a row in A as long as it’s not ref in B
I already did it but I’m looking for a better approach.
My approach
$referencesInB = TableB::where('a_id', $id)->exists();
if ($referencesInB) {
return response()->json(['error' => 'Cannot update'], 403);
}
$rowA->update($request->all());
2
Answers
You can do it upstream where you first get
$rowA
'B'
is the name of the relation difined in TableA model classYou can avoid the extra query check above(saving us a few milliseconds or more) by eager loading the relation and checking if the relation actually loaded. So, it all happens with 1 query instead of 2 eliminating the
N + 1
query issuedocs
.