Home  >  Q&A  >  body text

Access permissions queried in model.php file in Laravel

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;
    }]);
    }
}

P粉549412038P粉549412038235 days ago453

reply all(1)I'll reply

  • P粉674757114

    P粉6747571142024-02-27 15:27:52

    I think you are looking for hasManyThrough

    hasManyThrough(GrandChildren::class, Children::class);
        }
    }

    reply
    0
  • Cancelreply