I have a relationship and a function in my User.php;
class User extends Model { public function children() { return $this->hasMany(self::class, 'level1_user_id') ->select(['id', 'first_name', 'last_name', 'level1_user_id']); } public function grandchildren() { return $this->children()->with(['grandchildren']); } }
This is my controller.php:
public function allChildren() { $user = User::where('id', 3)->with(['grandchildren' => function ($query) { $query->where('first_name', 'rose'); } ])->first(); return $user; }
When I append the grandchild, it returns all the nodes of the tree; I want to assign a condition and get the node with name "rose" but I can only do this for the first level; how do I access this query:
$query->where('first_name', 'rose');
Can I also set up queries for others in my grandchild function in User.php?
I want to do something like this:
class User extends Model { public function children() { return $this->hasMany(self::class, 'level1_user_id') ->select(['id', 'first_name', 'last_name', 'level1_user_id']); } public function grandchildren(Query $inputQuery) { return $this->children()->with(['grandchildren' => function ($query) use ($inputQuery) { $query->$inputQuery; }]); } }
I think you are looking for hasManyThrough