PHP / Laravel构造ManyToMany关系的递归树

I have two tables with a ManyToMany relationship between them

Artist
id:unique id
qid:shared id
name:string

and

Influence
id:id
qid:shared id
name:string
is_person:boolean

Some of the names in the Influence table also exist in the Artist table and share a qid. I want construct a tree off all Artists and those they Influence who exist in the Artist DB. I want to recursively go through all the Influences and get their Influences nested under the parent. I don't know how deep each relationship will go.

public function getRelationships() {
    foreach($artists as $artist) {
        foreach($artist->influences as $influence) {
            if($influence->is_person) {
                $child = Artist::where('qid' , '=', $influence->qid);
                //somehow call getRelationships() here 
                //again with what I need to construct the relationship
                //tree
            }
        }
    }
}

I think this code work for you but you need to make a dumb artisan to be a father for your roots and need to pass it to function when you calling it

public function getRelationships($artist) {
   $returndata['Artist']=$artist;
    foreach($artist->influences as $influence) {
        if($influence->is_person) {
            $child = Artist::where('qid' , '=', $influence->qid);
            $returnData['influence'][]=getRelationships($child);
        }
   }
 return $returnData;
}

but i dont know what should i do if the influence is not person if you have problem comment for me!