How to see table fields from foreign keys in Laravel

后端 未结 3 803
小蘑菇
小蘑菇 2021-01-26 10:04

I\'m new at Laravel and not good with syntax. I want to see the values of another table through the foreign key(id of that table).

https://ibb.co/pXRFRHn You can see in

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-26 10:51

    You've to declare your relationships at all. In your User Model,

    public function class()
    {
        return $this->hasOne('App\Class');
    }
    

    and Class Model,

    public function users()
    {
        return $this->hasMany('App\User');
    }
    

    So after that you can call it like that;

    public function index()
    {
    
        $sections = Section::all();
        $classs = Classs::with('user')->get();
        $users = User::with('class')->get();
    
    
        return view('sections.index')
            ->with('sections', $sections)
            ->with('classs', $classs)
            ->with('users',$users);
    }
    

    Or you can call them when you're fetching in view just like that;

    @foreach($users->class()->get() as $class )
        {{ $class->name}}
    @endforeach
    
    @foreach($classes->users()->get() as $user )
        {{ $user->name}}
    @endforeach
    

    they called 'Eloquent Relationships' Laravel's Relationships

    just make sure you were read them because documentation is too much clear to understand something in record times.

    hasOne and hasMany are just just example. Which relation type works for you can change.

提交回复
热议问题