jeudi 23 juin 2016

Laravel 5.1 using morph relation with global scope

I have global scope on my Product model and method withChildren to get data over scope. All was ok, until i tried use it with morph relation.

Code

Scope code

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 method

public function scopeWithChildren()
{
    return with(new static)->newQueryWithoutScope(new ParentScope);
}

Scope injected in model through boot method, like so

protected static function boot()
{
    parent::boot();
    //exclude children products from all results by default
    Product::addGlobalScope(new ParentScope);
}

Problem

Relation returns null before i can implement my withChildren method. Invoice and Product have simple plymorphic relation.

$products = $invoice->products; //products is null, because of global scope

Tried

$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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire