samedi 2 juillet 2016

Laravel recursive relations with filter

I have following tables:

  1. organizations table which represents hierarchy (contains id and parent_id)
  2. budget_user_limits - organization_id (FK), limit_amount and budget_id (should filter by this column)

I have managed to create a function (currentUserOrganizationTree, code below) to retrieve hierarchy starting from $root. And I filtered limits by budget_id=1. Yet, I have two challenges:

  1. I don't know how to make this filter dynamic in terms that I need to use parameter from currentUserOrganizationTree($budget_id)
  2. root element does not get limits loaded -> this one should be easy but I don't know how to solve it elegantly

What I tried so far:

  1. passing filter value as parameter to all functions but with relations do not accept parameters. ->with('allChildren') dont know how to pass parameter to allChildren function
  2. creating instance level property and assign it budget_id so it can be used by subsequent executions of limits function. Yet it is instance level property and descendant Organization objects will not have it
  3. decided not to go with static property (as in previous item) since I believe it will not work properly in multiuser concurrent environment

Code (this is in Organization model):

public function childrenWithLimits()
{
    return $this->hasMany('App\Organization', 'parent_id', 'id')->orderBy('code');
}

public function allChildrenWithLimits()
{
    return $this->childrenWithLimits()->with('allChildrenWithLimits', 'limits');
}

public function limits()
{
    return $this->hasMany('App\BudgetUserLimit', 'organization_id', 'id')->where('budget_id', 1); // dynamic filter ($budget_id) should be used, not hardcoded
}

public static function currentUserOrganizationTree($budget_id)
{
    ... // logic to get $root is omitted
    $root = $root->get()->first(); // this one does not get limits loaded
    $root['all_children'] = $root->allChildrenWithLimits()->get();
    $arr = [$root];
    return $arr;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire