GON*_*ONG 6 laravel laravel-5.1
我在我的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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
withChildren 方法
public function scopeWithChildren()
{
return with(new static)->newQueryWithoutScope(new ParentScope);
}
Run Code Online (Sandbox Code Playgroud)
范围通过boot方法注入模型,如此
protected static function boot()
{
parent::boot();
//exclude children products from all results by default
Product::addGlobalScope(new ParentScope);
}
Run Code Online (Sandbox Code Playgroud)
问题
在我可以实现我的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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |