多对多表如何查看Laravel

时间:2018-07-13 07:11:39

标签: laravel

我有这三个表:

Table 1. users

'first_name', 'last_name', 'bio', 'image', 'email', 'password', 'user_group','remember_token',

Table 2. professions

'id', 'title',

Table 3 user_profesions

'id','user_id','profession_id'

我将users表与user_professions表合并,如下所示:

    public function index(){


        $mentors = User::where('user_group', 2)->get();



    $all_professions = Profession::get();

        foreach($mentors as $mentor) {
            $mentor->professions =  UserProfession::where('user_id', $mentor->id)->get();
        } 



dd($mentors);
        return view('mentors.list-of-mentors')->with(['mentors'=>$mentors, 'all_professions' => $all_professions]); 
    }

所以我在转储时死了

enter image description here

我也正在通过职业表格中的所有职业。 鉴于我正在这样做

  @foreach($mentors as $mentor)
{{$mentor->first_name}}
    @foreach($all_professions as $profession)
                {{$profession}}
                 @endforeach

@endforeach

我被困在这里,我不知道该如何使特定用户显示职业。.有人可以帮我吗?。

2 个答案:

答案 0 :(得分:2)

您可以使用雄辩的ManyToMany关系在UserProfession模型之间获取数据。为此,您必须像这样定义它

用户模型

public function professions()
{
    return $this->belongsToMany('App\Profession','user_profesions');
}

专业模式

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

现在在控制器中像这样获取它

$mentors = User::with('professions')->where('user_group', 2)->get();
return view('mentors.list-of-mentors')->with('mentors',$mentors); 

在视图中,您可以像这样使用它

@foreach($mentors as $mentor)
      {{$mentor->first_name}}
      @foreach($mentor->professions as $profession)
           {{$profession}}
      @endforeach
@endforeach

在此处https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

答案 1 :(得分:0)

将关系数学方法添加到模型中。 UserModel

public function professions()
{
    return $this->hasMany(Profession::class);
}

ProfessionModel:

public function users()
{
    return $this->hasMany(User::class);
}

现在您可以执行以下操作:

$user = User::where('user_group', 2)->with('professions')->get();
dd($user->professions);