Eloquent morphTo()->withTrashed() stopped working

坚强是说给别人听的谎言 提交于 2021-01-06 04:24:07

问题


I have a polymorphic relationship set up in an OrderItem model, where saleable can be a few different models.

I've set it up like any other relationship:

public function saleable()
{
    return $this->morphTo()->withTrashed();
}

This used to work fine, now all of a sudden it doesn't work and it throws the error:

Call to undefined method Illuminate\Database\Query\Builder::withTrashed()

I don't understand why it would have stopped working, possibly due to a composer update which may have updated Laravel. I'm on v5.2.35. Any idea why it would have stopped working and what other solutions do I have?

UPDATE

Works fine with v5.2.33 and earlier. May be a bug, I've opened an issue on github


回答1:


The only thing I could imagine is that you removed SoftDelete trait for the object, so it's not loaded any more or you've added boot method that doesn't inherit from parent (so it won't load proper methods from this trait)

EDIT

It seems to be a bug introduced in v5.2.34. It seems to be fixed in this PR https://github.com/laravel/framework/pull/13828

EDIT

It should be fixed at the moment. v5.2.36 has been released.




回答2:


I dug through the code and found a solution! This solution is for my issue, where some models can be soft deleted and others cannot.

use Illuminate\Database\Eloquent\SoftDeletingScope;
//...
public function mySometimesSoftDeletableRelation(){
    return $this->morphTo()->withoutGlobalScope(SoftDeletingScope::class);
}

At its core, withTrashed uses unset, which doesn't care if it's unsetting something which isn't set, so this removes the SoftDeletingScope on those models which have it, and does nothing for others.



来源:https://stackoverflow.com/questions/37646003/eloquent-morphto-withtrashed-stopped-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!