Load does not work for dynamical relationships?

Imagine you have the following two relations:

 /**
 * Relation working/holiday/.. hours
 * @return [type] [description]
 */
public function relatedHours($type = null)
{
  $type = $type ?? $this->type;
  return $this->hours()->where('type', '=', $type);
}

 public function workingHours()
 {
  return $this->relatedHours(Type::WORK);
}

Only a fool would belive that the following method would load the same relations for ' workingHours' and 'relatedHours' :

public function loadHours()
{
     $this->type = Type::WORK;
    $this->load('workingHours');
    $this->load('relatedHours');
}

Infact, when we use the load method on a relation, then $this is just an instance of the class without attributes. Same seems to be the case for eager loading (https://stackoverflow.com/questions/35438254/laravel-dynamic-relationships-access-model-attributes-on-eager-load).

In other words, relatedHours will be an empty collection or null (depends if it is hasMany or hasOne), while workingHours will link to the relation (if there exists any).

Leave a comment

Your email address will not be published. Required fields are marked *