我的Product
模型和方法withChildren
具有全局范围,可以在范围内获取数据。一切都很好,直到我尝试使用变形关系。
代码
范围代码
public function apply(Builder $builder, Model $model)
{
return $builder->whereNull('parent_id');
}
/**
* Remove the scope from the given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function remove(Builder $builder, Model $model)
{
$query = $builder->getQuery();
foreach ((array) $query->wheres as $key => $where)
{
if($where['column'] === 'parent_id')
{
unset($query->wheres[$key]);
$query->wheres = array_values($query->wheres);
}
}
}
withChildren
方法
public function scopeWithChildren()
{
return with(new static)->newQueryWithoutScope(new ParentScope);
}
通过boot
方法在模型中注入的范围,如此
protected static function boot()
{
parent::boot();
//exclude children products from all results by default
Product::addGlobalScope(new ParentScope);
}
问题
在我实现withChildren
方法之前,Relation返回null。发票和产品具有简单的plymorphic关系。
$products = $invoice->products; //products is null, because of global scope
试过
$invoice->products()->withChildren()->get() //500 error without any description
$invoice->with('products', function($q) {$e->withChildren();})->get(); //explode() expects parameter 2 to be string, object given