cybercog / laravel-ownership

Laravel Ownership simplify management of Eloquent model's owner.
https://komarev.com/sources/laravel-ownership
MIT License
89 stars 16 forks source link

Behavior with softDeletes #20

Closed ghost closed 6 years ago

ghost commented 6 years ago

So, if anyone have similar issues, plz tell me.

My models are:

User implements CanBeOwner contract Profile use HasOwner trait

Both use SoftCascadeTrait

// in User model 
public function profile(): HasOne
{
    // using withTrashed() here
    return $this->hasOne(Profile::class, 'owned_by_id')->withTrashed();
}

But for Profile model, I don't set this association cause it's already handled by the trait.

The problem is, when fetching Profile content, I need to configure it everytime using ->with().

$profiles = Profile::withTrashed()->with(['owner' => function ($query) {
    $query->withTrashed(); // not filtering trashed owners
}])->get();

I just wanna to simplify, call it directly and stay not filtering trashed records. Any thoughts?

antonkomarev commented 6 years ago

You can add custom relationship to your Profile model which will call owner relationship under the hood with withTrashed() scope. Like you've done with profile relation in User model.

ghost commented 6 years ago

Yea, I thought about that but I was wondering if it's really a good idea. Seems kind of a "hacky" solution for me...

Anyway, I probably will opt for this solution.

Thanks for your comment.

antonkomarev commented 6 years ago

I'm closing this issue. If you have more ideas how to solve it - feel free to continue conversation.

ghost commented 6 years ago

Ok thanks! Just to note here, the final solution is:

    /**
     * Overrides the owner relationship from HasOwner trait adding trashed items.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function owner()
    {
        return $this->ownedBy()->withTrashed();
    }