Laravel 5.1使用全局范围的变形关系

时间:2016-06-23 11:28:18

标签: 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);
        }
    }
}

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

0 个答案:

没有答案
相关问题