Home > Enterprise >  access to query in model.php laravel
access to query in model.php laravel

Time:06-17

I have a relation 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']);
    }
}

and 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 attach grandchildren it returns all nodes of that tree; I want to assign a condition and get nodes that their name is 'rose', but I can do this just for first level; how can I access this query:

 $query->where('first_name', 'rose');

in my User.php in grandchildren function to set the query for others too?

I want to do sth 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;
    }]);
    }
}

CodePudding user response:

I think you're looking for hasManyThrough

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class User extends Model
{
    public function grandchildren()
    {
        return $this->hasManyThrough(GrandChildren::class, Children::class);
    }
}

CodePudding user response:

Given your users table, with foreign key level1_user_id linking to other users instances in order to establish direct parental relationship, you could setup your User Laravel model as follows:

class User extends Model
{
    /**
     * Get the user's direct children.
     */
    public function children()
    {
        return $this->hasMany(self::class, 'level1_user_id');
    }
}

Notice how we simply define how one User instance can be parent of other User instances. We don't mix in query logic, unlike how you use ->select() and ->with(). That's a good thing as it decouples your query concern from relationships' definitions.

Now in your controller, you can query a user while including its children, and while being able to customize the children's query, by doing the following:

use Illuminate\Database\Eloquent\Relations\Relation;

$user = User::with([
    'children' => function (Relation $query) {                               //            
  • Related