laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.55k stars 11.03k forks source link

Bug with MorphToMany and softDelete #29015

Closed MatheusAMFB closed 5 years ago

MatheusAMFB commented 5 years ago

Description:

In my system there is a 'channels' and 'channelables' table they have a 'MorphToMany' relation. Channels does not have softdelete since it is not possible to delete. Channelable can be deleted with softDeletes. What happens is that when some channelable is deleted the relationship remains intact.

Channable trait /**

Where the relation was to be deleted

/**
 * Effectivelly sync channels relations to channelable model.
 *
 * @param \App\Models\Contracts\Channelable $channelable
 * @param iterable|\App\Models\Channel[]    $channels
 *
 * @return \Illuminate\Support\Collection|\App\Models\Channelable[]
 */
private function sync(ChannelableContract $channelable, iterable $channels)
{
    $channelables = collect([]);

    foreach($channels as $channel) {
        $channelables->push(
            ChannelableModel::query()->firstOrCreate([
                'channelable_id' => $channelable->getKey(),
                'channelable_type' => $channelable->getMorphClass(),
                'channel_id' => $channel->getKey()
            ])
        );
    }

    ChannelableModel::query()
        ->whereKeyNot($channelables->pluck('id')->all())
        ->where('channelable_id', $channelable->getKey())
        ->where('channelable_type', $channelable->getMorphClass())
        ->get()
        ->each
        ->delete();

    return $channelables;

And in the table the column 'deleted_at' is filled in properly with the date. But when I use anything involving this relation, it's as if nothing has been deleted.

staudenmeir commented 5 years ago

Laravel doesn't support SoftDeletes on pivot tables: #14008 #20307

You can try this package: https://github.com/mlezcano1985/laravel-pivot-soft-deletes

driesvints commented 5 years ago

Also please see the note about this at the end of https://laravel.com/docs/5.8/eloquent-relationships#defining-custom-intermediate-table-models