问题
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