I have defined my Category
model this way:
class Category extends Eloquent
{
public function parent()
{
return $this->belongsTo('Category', 'par_cat');
}
public function children()
{
return $this->hasMany('Category', 'par_cat', 'id');
}
public function scopeVisible($q)
{
return $q->whereActive(1)->whereAccepted(1);
}
public function scopeDefOrder($q) {
return $q->orderBy('priority', 'ASC')->orderBy('name','ASC');
}
}
Now when I want to get visible categories with predefined orderby using scope I can do something like this:
$categories = Category::visible()->defOrder()->get();
But what in case if I want to get also visible children?
I could use syntax like this:
$categories = Category::with(['children' =>function($q) {
$q->visible()->defOrder();
}])->visible()->defOrder()->get();
but it seems to be a bit too complicated to use only scope for children. Is there any other way? I could imagine using for example:
$categories = Category::with('children#visible#defOrder')
->visible()->defOrder()->get();
but probably there is no such construction.
The only solution I found is creating one more extra relationship:
public function visibleDefOrderChildren()
{
return $this->children()->visible()->defOrder();
}
and now I can also use:
$categories = Category::with('visibleDefOrderChildren')->visible()->defOrder()->get();
but in case I had more scopes and not use always visible
scope with defOrder
scope, it wouldn't make sense creating dozens methods just to use scopes for relationship.
Is there any other simpler solution? Or I have choose between closure and creating extra methods to append scopes to relationship?