Using the same model for a relation, scope a subset


Let’s say I have a model called “Company”. In the table, I have these columns:

ID description parent_account attached_to_parent_account
1 Company A 100 null
2 SubCompanyX A null 100
3 SubCompanyY A null 100

Now, I would like to add a relation in my Company model to return all the subcompany.

If I’m in Company A (ID:1), I would like to get 2 items, which are the ID 2 and 3.

  public $hasMany = [
        'subcompanies' => [
            'key' => 'id',
            'scope' => [self::class, 'getSubcompanies']
 public static function getSubcompanies($query, $related, $parent)
        return $query->where('attached_to_parent_account', $parent->parent_account);

It’s not working, it’s looking to match on the ID, which will return the company ID 1.

If anybody has an idea, thanks to share! (I also tried with SimpleTree, it was not working either).