【问题标题】:How to view all fields with more than 3 tables laravel如何查看超过3个表的所有字段laravel
【发布时间】:2018-12-20 16:34:57
【问题描述】:

您好,有人可以帮帮我我是 laravel 的新手,我有这三个表:

表 1. 用户

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

表 2. 职业

'id','标题',

表 3 user_profesions

'id','user_id', 'profession_id'

如何获取所有这些字段并显示而不是查看 我在 Controller 上开始了这样的事情:

 public function index(){


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



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

但这只是来自表导师,我希望能够将具有多个职业的用户的字段发送到视图

【问题讨论】:

    标签: laravel


    【解决方案1】:

    试试下面 还要确保您的 UserProfession 模型与 User 和 Profession 具有 belongsTo 关系

    UserProfession.php 模型

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
    
    public function profession()
    {
        return $this->belongsTo(Profession::class, 'profession_id');
    }
    

    你的代码

    UserProfession::with('user', 'profession')
        ->whereHas('user', function ($q) {
            $q->where('user_group', 2);
        })
    ->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多