jeudi 4 juillet 2019

How to get data from one to many relations table in laravel

Hierarchies table: enter image description here

here up and down columns are referred user_id of users table. suppose I have the following data:

    id  up  down
--------------------
    1   1    2
    2   1    3
    3   1    5
    4   2    4

I want to relate subordinate inside Hierarchy model as follows:

class Hierarchy extends Model
{
     protected $attributes = [
       'status' => 1
    ];
    protected $fillable = [
        'up', 'down', 'created_at','updated_at'
    ];

    public function subordinates(){
     return $this->hasMany('App\User', 'id', 'down');
    }
}

Now I want to get all users where hierarchies.up=1. For the above data I will get user info having user_id(down) = 2,3,5. And I am trying as follows:

$loggedInUserId = Auth::user()->id;
     $subordinate=Hierarchy::where('up',$loggedInUserId)->subordinates()->get()->toArray();//subordinates()->get()->toArray();
     echo "<pre>";
     print_r($subordinate);
     echo "</pre>";
     return view('goal.create')->with('data',$subordinate);

But subordinate method is undefined in this context. Whats wrong in my approach?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/329CW75
via IFTTT

Aucun commentaire:

Enregistrer un commentaire