【问题标题】:Many to many tables how to view on Laravel多对多表如何在 Laravel 上查看
【发布时间】:2018-07-13 16:22:01
【问题描述】:

我有这三张桌子:

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

所以当我死的时候它给了我这个

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

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

@endforeach

我被困在这里我不知道如何让特定用户出现的职业..有人可以帮我..吗?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您可以使用 eloquent 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

    【讨论】:

    • 它给了我这个foreach的错误($mentor->professions as $profession 它说语法错误,意外的'foreach'(T_FOREACH)
    • 你添加关系了吗?
    • 它是;死后你忘了
    • 你需要删除,dd 和 php foreach 只是为了让我更新
    【解决方案2】:

    为您的模型添加关系数学。 用户模型

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

    职业模型:

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

    现在你可以这样做了:

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

    【讨论】:

      猜你喜欢
      • 2021-03-16
      • 2012-08-05
      • 1970-01-01
      • 2018-11-21
      • 2016-05-18
      • 2013-03-05
      • 2018-10-07
      • 1970-01-01
      • 2017-09-30
      相关资源
      最近更新 更多