Closed goldmont closed 4 weeks ago
Forgot to say... labels
relation is a morphToMany
UPDATE:
Reading the source of BelongsOrMorphsToMany
, I saw the following:
If a custom pivotModel is being used the parameters will actually be
string $relationName, mixed $id, array $attributes
I'm not using a custom pivot model because I haven't either specified it. This is the configuration of my relation:
public $morphToMany = [
'labels' => [
Label::class,
'name' => 'labelable',
'table' => 'company_management_labelables',
'timestamps' => true
]
];
UPDATE 2:
Apparently Morphs
are using a default Pivot
model if not specified. That's why I'm getting a single ID at a time instead of all IDs. I don't know how it can be improved at the moment (if it can be).
This is how Laravel implemented sync()
, not a bug.
How can I determine which labels have been removed and which ones have been added? My task involves notifying task assignees that certain labels have been removed while others have been added. The sync()
method provides an array of detached IDs via afterDetach
, but it only gives one ID at a time for attached ones. Should I collect them individually, or is there a more efficient method?
Hi there,
I forgot to get back to you. Ultimately, I decided to manually diff the two collections and use attach
/ detach
directly. For anyone who needs this:
$ids = $task->assignees()->pluck('id');
$newIds = collect(array_unique($data['assignees'], SORT_NUMERIC));
if (!empty($toDetach = $ids->diff($newIds)->all())) {
$task->assignees()->detach($toDetach);
}
if (!empty($toAttach = $newIds->diff($ids)->all())) {
$task->assignees()->attach($toAttach);
}
Winter CMS Build
1.2
PHP Version
8.1
Database engine
MySQL/MariaDB
Plugins installed
No response
Issue description
Hi,
I noticed a difference in how
model.relation.afterAttach
andmodel.relation.afterDetach
events behave. It sounds more like a bug than something wanted.I have a custom trait attached to my model and two listeners: one for afterAttach and another for afterDetach:
In my API I simply do the following:
This is the output:
The
afterAttach
listener is invoked for every new relation; instead, theafterDetach
listener is invoked only once and it receives an array of ids as expected. I made some mistake in my configuration or is it a bug? Thank you for your efforts as always.Steps to replicate
afterAttach
andafterDetach
listeners.sync
method.Workaround
No response