Question about saveAssociates

Is there a way with an associated model to determine whether a save was triggered by the model itself, or its parent?

So for example - I have a “Member” who HasMany “MemberStatuses”

During the initial create, the “Member” and the initial “MemberStatus” is created. Subsequently I can add a new “MemberStatus”. Can I ascertain whether the MemberStatus save was create as a result of a Member save with associated models?

Reason I ask is I need to determine the in the afterSave for the “MemberStatuses” and have different logic accordingly.

Thanks in advance :slightly_smiling_face:

Possibly with a created_at timestamp.

I can’t remember the specifics right now, but I think there’s something added to the $options that get passed to the various event handlers (e.g. afterSave) that indicates whether the operation is happening for the top-level entity or an association.

Cool thanks - found there’s a _sourceTable property in $options that tells me the source table instance for the save event, and also a _primary property - can’t find too much documentation on this other than it’s set to false on a save via association

Sometimes it seems like a lot of what I do is


“oh ok - now I see what it’s doing…” :stuck_out_tongue:

_primary is what I was thinking of, but depending on your use case, _sourceTable might be more appropriate. Or, you might want to add your own custom option when saving with one method vs the other and check for that.

debug($options); is super useful, until you get xdebug working, and then you wonder why you wasted so much time with debug() statements. :slight_smile:

1 Like

I add options manually
'$this->save($var,['skipAfterSave' => true]);
and have
if (isset($options['skipAfterSave'])) return;
at beginning of my model events.

1 Like

_primary seems to have done the trick

Checking out xdebug is on the list of things to do during the holiday break, heard many good things about it, although also heard tricky to set up.

Lots of debug('got to here'); in a pinch when you’re lazy :wink:

Worked with a French speaking programmer last century, you would find PRINT "MERDE" sprinkled through his code. Occasionally he left it in code that shipped and I’d get a call from a client “Program has hung and there’s an error code on screen, M-E-R-D-E. What does that mean?”

change it to PRINT "MERDE ".__LINE__ and it will be good :wink:

1 Like